如何删除Matplotlib

时间:2016-11-03 19:44:49

标签: python matplotlib

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

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的情节更窄更窄。 现在,如果我想用计数器绘图做一些工作,而不是只需要在“行”之后删除逗号。根据我的理解,这个小修改来自于计数器图不再是元组的元素,而只是一个属性,因为计数器图完全“填满”所有可用空间。

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

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()

无论我是否输入逗号都没关系,我只是收到错误消息。 你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

ax.hist不会返回您的想法。

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

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]

答案 1 :(得分:1)

这是在matplotlib中迭代绘制和删除直方图的正确方法

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize = (20, 10))
ax = fig.add_subplot(111)
ax.grid(True)


for j in range(1, 15):
    x = np.random.randn(100)
    count, bins, bars = ax.hist(x, 40)
    plt.draw()
    plt.pause(1.5)
    t = [b.remove() for b in bars]