首页 > 解决方案 > 如何清除 matplotlib 子图中的直方图

问题描述

我正在尝试在单个图形上浏览一系列直方图。最终,我将拥有一个按钮,可以让我在系列中向前或向后移动。但是,目前,我无法清除当前的直方图,以便为下一个直方图让路。

我的基本方法如下:

fig, ax = plt.subplots(1)
ax.hist(hist1)
fig.show() # This successfully displays my histogram
ax.clear()
fig.show() # The histogram is still present. Clearing was ineffective.

如何清除坐标轴,以便图形为下一个直方图做好准备?


一个最小的、完整的和可验证的例子:

me@home:~/Projects/kerasECOC$ python
Python 2.7.14 |Anaconda custom (64-bit)| (default, Dec  7 2017, 17:05:42) 
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> a = np.random.randn(100)
>>> fig, ax = plt.subplots(1)
>>> ax.hist(a)
(array([ 7.,  4., 16., 11., 15., 16., 17.,  8.,  3.,  3.]), array([-1.96828374, -1.54116206, -1.11404039, -0.68691871, -0.25979703,
        0.16732464,  0.59444632,  1.02156799,  1.44868967,  1.87581134,
        2.30293302]), <a list of 10 Patch objects>)
>>> fig.show()
>>> ax.clear()
>>> fig.show() #Figure is unchanged. I expected a blank fig as in ImportanceOfBeingErnest's example
>>> plt.__version__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'
>>> import matplotlib
>>> matplotlib.__version__
'2.2.2'
>>> 

标签: pythonmatplotlib

解决方案


推荐阅读