首页 > 解决方案 > Matplotlib 修改直方图修改后不显示

问题描述

我已经绘制了一个直方图并想修改它,然后重新绘制它。Figure如果不重新定义和Axes对象定义,它将不会再次绘制。我正在使用 Jupyter Notebook,而且我是 matplotlib 的新手,所以我不知道这是否是我对 matplotlib 不了解的地方,是否是 Jupyter Notebook 的问题或其他问题。

这是我的第一个代码块:

"""Here's some data."""
some_data = np.random.randn(150)
"""Here I define my `Figure` and `Axes` objects."""
fig, ax = plt.subplots()
"""Then I make a histogram from them, and it shows up just fine."""
ax.hist(some_data, range=(0, 5))
plt.show()

这是我的第一个代码块的输出:

Histogram_output_1

这是我的第二个代码块:

"""Here I modify the parameter `bins`."""
ax.hist(some_data, bins=20, range=(0, 5))
"""When I try to make a new histogram, it doesn't work."""
plt.show()

我的第二个代码块没有产生可见的输出,这就是问题所在

这是我的第三个也是最后一个代码块:

"""But it does work if I define new `Figure` and `Axes` objects. 
Why is this? 
How can I display new, modified plots without defining new `Figure` and/or `Axes` objects? """
new_fig, new_ax = plt.subplots()
new_ax.hist(some_data, bins=20, range=(0, 5))
plt.show()

这是我的第三个也是最后一个代码块的输出:

Histogram_from_3rd_block

提前致谢。

标签: matplotlibjupyter-notebookhistogram

解决方案


当您生成图形或轴时,它仍可用于渲染或显示,直到它用于渲染或显示。一旦你plt.show()在你的第一个块中执行,ax就会变得不可用。您的第三个代码块显示了一个绘图,因为您正在重新生成图形和轴。


推荐阅读