Matplotlib修改后的直方图在修改后将不会显示

时间:2019-09-24 13:29:23

标签: matplotlib jupyter-notebook histogram

我已经绘制了直方图,想要对其进行修改,然后重新绘制。如果不重新定义FigureAxes对象定义,它将不会再次绘制。我正在使用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

谢谢。

1 个答案:

答案 0 :(得分:0)

生成图形或轴时,在用于图形显示或显示之前,图形或轴仍可访问。在第一个程序段中执行plt.show()后,ax将不可用。您的第三个代码块显示了一个图,因为您正在重新生成图形和轴。