2014-01-25 58 views
2

我正在編輯我的圖一步一步。這樣做,plt功能從matplotlib.pyplot立即適用於我的圖形輸出的pylab。那很棒。爲什麼pyplot方法立即適用,子圖軸方法不適用?

如果我處理一個子圖的座標軸,它就不會再發生了。 請在我最小的工作示例中找到兩個替代方案。

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 

f = plt.figure() 
sp1 = f.add_subplot(1,1,1) 
f.show() 

# This works well 
sp1.set_xlim([1,5]) 

# Now I plot the graph 
df = pd.Series([0,5,9,10,15]) 
df.hist(bins=50, color="red", alpha=0.5, normed=True, ax=sp1) 

# ... and try to change the ticks of the x-axis 
sp1.set_xticks(np.arange(1, 15, 1)) 
# Unfortunately, it does not result in an instant change 
# because my plot has already been drawn. 
# If I wanted to use the code above, 
# I would have to execute him before drawing the graph. 

# Therefore, I have to use this function: 
plt.xticks(np.arange(1, 15, 1)) 

我明白,有matplotlib.pyplotaxis實例之間的差異。我錯過任何東西還是隻是這樣工作?

回答

1

大多數pyplot功能(如果不是全部)必須在返回前plt.draw_if_interactive()通話。所以,如果你這樣做

plt.ion() 
plt.plot([1,2,3]) 
plt.xlim([-1,4]) 

你得到的情節是隨時更新。如果您關閉了互動功能,則不會創建或更新劇情,除非您不撥打plt.show()

但是所有的pyplot函數都是相應的(通常是)Axes方法的包裝。

如果你想使用OO接口,並且還畫出的東西,你輸入,你可以做這樣的事情

plt.ion() # if you don't have this, you probably don't get anything until you don't call a blocking `plt.show` 
fig, ax = plt.subplots() # create an empty plot 
ax.plot([1,2,3]) # create the line 
plt.draw() # draw it (you can also use `draw_if_interactive`) 
ax.set_xlim([-1,4]) #set the limits 
plt.draw() # updata the plot 

您不必使用你不想pyplot,只是請記住draw

1

plt.xticks()方法調用函數draw_if_interactive()來自pylab_setup(),他正在更新圖形。爲了使用sp1.set_xticks()做到這一點,只需調用相應的show()方法:

sp1.figure.show() 
+0

'show'阻塞,當我從python使用它。它不會阻止ipython,但我想是由於我的設置。和'f.show()'就足夠了 –

+1

+1爲背景信息 – Xiphias

相關問題