Reputation: 2217
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()
I am struggling in particular with feeding my desiredentropies
list which depends on the element in the time
list for the animation.
Upvotes: 14
Views: 12898
Reputation: 1849
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()
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.
Upvotes: 10