Matplotlib动画直方图 [英] Matplotlib animated histogram

查看:202
本文介绍了Matplotlib动画直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据下面的代码创建动画直方图。我可以每次创建单独的直方图,但是我无法使用 matplotlib.animation 函数或模拟 matplotlib教程

I am trying to create an animated histogram from my code below. I can create individual histograms for each time however I cannot get the results to be animated with the matplotlib.animation function or from emulating the code in the 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 列表中的元素

I am struggling in particular with feeding my desiredentropies list which depends on the element in the time list for the animation.

推荐答案

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

Try this. This basically just leverages FuncAnimation to let you update the histogram. Check out the animation documentation to learn more about the various parameters to that function to control the speed of update and stuff like that.

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 索引到我们的数据中,这是当前的帧编号。

What we do here is call a function, update_hist which handles updating the histogram and displaying the new data at each step. We do this by clearing the axis and then indexing into our data with the provided num, which is the current frame number.

这篇关于Matplotlib动画直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆