如何在 Matplotlib 中删除直方图

2023-12-05

我习惯于处理随时间变化的图,以便在参数更改时显示差异。这里我提供一个简单的例子

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(True)

x = np.arange(-3, 3, 0.01)

for j in range(1, 15):
    y = np.sin(np.pi*x*j) / (np.pi*x*j)
    line, = ax.plot(x, y)
    plt.draw()
    plt.pause(0.5)
    line.remove()

您可以清楚地看到,随着参数 j 的增加,绘图变得越来越窄。 现在,如果我想用计数器图来做一些工作,那么我只需删除“line”后面的逗号即可。根据我的理解,这个小小的修改来自这样一个事实:计数器图不再是元组的元素,而只是一个属性,因为计数器图完全“填满”了所有可用空间。

但看起来没有办法删除(并再次绘制)直方图。事实上如果输入

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(True)

x = np.random.randn(100)

for j in range(15):
    hist, = ax.hist(x, 40)*j
    plt.draw()
    plt.pause(0.5)
    hist.remove()

无论我是否输入该逗号,我都会收到一条错误消息。 你能帮我解决这个问题吗?


ax.hist不会返回您认为的结果。

文档字符串的返回部分hist(通过访问ax.hist?在 ipython shell 中)指出:

Returns
-------
n : array or list of arrays
    The values of the histogram bins. See **normed** and **weights**
    for a description of the possible semantics. If input **x** is an
    array, then this is an array of length **nbins**. If input is a
    sequence arrays ``[data1, data2,..]``, then this is a list of
    arrays with the values of the histograms for each of the arrays
    in the same order.

bins : array
    The edges of the bins. Length nbins + 1 (nbins left edges and right
    edge of last bin).  Always a single array even when multiple data
    sets are passed in.

patches : list or list of lists
    Silent list of individual patches used to create the histogram
    or list of such list if multiple input datasets.

所以你需要解压你的输出:

counts, bins, bars = ax.hist(x, 40)*j
_ = [b.remove() for b in bars]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Matplotlib 中删除直方图 的相关文章

随机推荐