2014-01-25 83 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

相关问题