2014-01-10 12 views
0

我試圖繪製一個在matplotlib上有兩個x軸的圖。但是,它不表現我將如何指望它在matplotlib上創建2個x軸不工作

import matplotlib.pyplot as plt 
import numpy as np 

fig = plt.figure() 
ax1 = fig.add_subplot(111) 
x = np.linspace(-10,10,1000) 
y = np.sin(x*np.pi/2) 
ax1.plot(x,y) 

ax2 = ax1.twiny() 
tick_locations = ax1.get_xticks() - 5. 
tick_labels = ax1.get_xticks() 

ax2.set_xticks(tick_locations[1:]) 
ax2.set_xticklabels(tick_labels[1:]) 

plt.show() 

給出:

enter image description here

不應該AX2標籤寫着:[ -5. 0. 5. 10.]在AX1位置[-10. -5. 0. 5.]

任何想法,爲什麼它的伸出他們?

回答

0

編輯代碼:

ax2.set_xticks(tick_locations[:]) 
ax2.set_xticklabels(tick_labels[1:]) 

編輯: 「根據卡拉伽馬對this後的反應看來你應該能夠選擇任何打勾位置?」

請注意,有他的代碼ax2.set_xlim,所以你也可以這樣做:

ax2.set_xlim(tick_locations[0], tick_locations[-1]) 
ax2.set_xticks(tick_locations[1:]) #1, not 0 
ax2.set_xticklabels(tick_labels[1:]) 

我覺得關鍵是你應該讓你的AX2 XLIM相同的範圍AX1。

+0

基於卡拉加馬的迴應[這篇文章](http://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib)它似乎你應該能夠選擇任何勾號位置? – Ben

+0

@Ben回答更新,使用'set_xlim' – zhangxaochen

+0

看起來'set_xlim'需要在'set_xticks'之後。其他明智的'set_xticks'重新定義了限制。但是你是對的,那是問題所在。 – Ben