python - Matplotlib 动画直方图

标签 python animation matplotlib

我正在尝试根据下面的代码创建一个动画直方图。我可以为每次创建单独的直方图,但是我无法使用 matplotlib.animation 函数或模拟 matplotlib tutorial 中的代码来为结果设置动画。 .

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 列表中的元素。

最佳答案

试试这个。这基本上只是利用 FuncAnimation 让您更新直方图。查看animation documentation了解有关该函数的各种参数的更多信息,以控制更新速度和类似内容。

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(当前帧编号)索引我们的数据。

关于python - Matplotlib 动画直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35108639/

相关文章:

python - 当满足特定条件时从列表创建新列表

python - 如何为每个项目调用 Parse_page2 方法

android - 多个动画同时运行时动画断断续续

python - HoughCircles的'NoneType'对象不是下标错误

jquery - 滚动 jquery 动画缺少 div

css - 更改 svg 描边动画的起点

python - matplotlib 图中等距网格线

python - Matplotlib:给Figure.add_subplot()的3位参数的含义是什么?

python - 创建一个包含打印输出和绘图的文件

python - 我如何使用 python 2.6 安装 zope 接口(interface)?