Matplotlib动态直方图

14

我正在尝试从下面的代码创建一个动态直方图。我可以为每个时间创建单独的直方图,但是我无法通过matplotlib.animation函数或从模拟matplotlib教程中的代码来实现动画效果。

import numpy as np
import matplotlib.pyplot as plt


betas = [] # some very long list
entropy = [] # some very long list

for time in [0.0, 0.5, 1.0, 1.5,  2.0, 2.5, 3.0 , 3.5,  4.0, 4.5  5.0, 5.5,   6.0, 6.5 , 7.0, 7.5,  8.0 , 8,5 , 9.0, 9.5 , 10.0]:

    plt.figure('entropy distribution at time %s ' % time)        
    indexbetas = {i for i, j in enumerate(betas) if j == time}
    desiredentropies = [x for i, x in enumerate(entropy) if i in indexbetas] #the desiredentropies list depends on time

    n, bins, patches = plt.hist(desiredentropies, 20, alpha=0.75 , label = 'desired entropies')   

plt.xlabel(r"$S_{(\time=%d)}$" % time, fontsize=20)
plt.ylabel('Frequency of entropies')


plt.legend()
plt.grid(True)
plt.show()

我在特定的问题上遇到了困难,那就是如何填充我的 desiredentropies 列表,这个列表依赖于动画中 time 列表中的元素。


教程中的示例需要几秒钟才能运行,但对我来说有效 - Python 2.7.11和3.4.3 / Linux Mint 17。您在控制台/终端/cmd.exe中是否收到任何错误消息? - furas
@furas 我在我的原始帖子中添加了一个编辑。我的主要问题是如何提供更新后的期望熵列表,我想制作一个直方图,随着时间的推移而变化。请注意:每个元素的期望熵列表都会随时间而改变。 - piccolo
你将必须使用 animation.FuncAnimation - furas
@furas 我理解下面的例子,但在这种情况下,我该如何更新我的update_hist以用于FuncAnimation函数。 - piccolo
animation.FuncAnimation 作为 for 的替代品。你必须使用它来替换 foranimation.FuncAnimation 会多次调用你的代码,并传入不同的值(即时间),每次调用后都会有一小段延迟,以便你可以看到它的动画效果。 - furas
@furas 这有点不同。时间列表元素是浮点数而不是整数,我的实时列表长度至少为一千。因此,延迟也不是理想的选择。 - piccolo
1个回答

10

试一下这个。这基本上只是利用FuncAnimation来让你更新直方图。查看动画文档以了解有关该函数的各种参数的更多信息,以控制更新速度等。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

n = 100
number_of_frames = 10
data = np.random.rand(n, number_of_frames)

def update_hist(num, data):
    plt.cla()
    plt.hist(data[num])

fig = plt.figure()
hist = plt.hist(data[0])

animation = animation.FuncAnimation(fig, update_hist, number_of_frames, fargs=(data, ) )
plt.show()

我们在这里所做的是调用一个名为update_hist的函数,该函数负责更新直方图并在每个步骤中显示新数据。我们通过清除轴,然后使用提供的num对数据进行索引,即当前帧数。


我该如何更新我的新期望熵列表,因为该列表取决于时间,即时间列表中的元素? - piccolo
将您的索引规范化为整数,并将代码放入“update_hist”中的“for”循环中。 - Alex Alifimoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接