【发布时间】:2020-01-24 15:29:42
【问题描述】:
我已经绘制了一个直方图并想对其进行修改,然后重新绘制它。如果不重新定义 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()
这是我的第一个代码块的输出:
这是我的第二个代码块:
"""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()
这是我的第三个也是最后一个代码块的输出:
提前致谢。
【问题讨论】:
-
您正在使用内联后端;所以你可以在第二个代码块中用
fig替换plt.show()。 -
感谢@ImportanceOfBeingEarnest。我按照您的建议做了并使用了
fig而不是plt.show()(您可以看到我在下面的代码块中注释掉了plt.show())。问题是新修改的情节位于原始情节之上。有没有办法用修改后的情节替换原来的情节?这是代码:ax.hist(some_data, bins=20, range=(0, 5))# plt.show()fig这是输出Modified Hist -
如果不创建新图,会显示在旧图上,是的。
标签: matplotlib jupyter-notebook histogram