Skip to main content
 首页 » 编程设计

python之为什么 pyplot 方法立即应用而 subplot 轴方法不应用

2024年11月01日10bonelee

我正在逐步编辑图表。这样做,matplotlib.pyplot 中的 plt 函数立即应用于我的 pylab 图形输出。太好了。

如果我处理子图的轴,它就不会再发生了。 请在我的最小工作示例中找到这两种选择。

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.pyplot 和 axis 实例之间存在差异。我错过了什么或者它只是这样工作的吗?

请您参考如下方法:

大多数 pyplot 函数(如果不是全部)在返回之前都会调用 plt.draw_if_interactive()。所以如果你这样做

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

您会发现情节会随着您的进行而更新。如果您关闭了交互,它不会创建或更新绘图,直到您不调用 plt.show()。

但所有 pyplot 函数都是相应(通常)Axes 方法的包装器。

如果你想使用 OO 接口(interface),并且仍然在你输入的时候画东西,你可以这样做

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