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.
To animate the histogram, we need an animate function, which generates a random set of numbers and updates the heights of rectangles. We utilize a python closure to track an instance of BarContainer whose Rectangle patches we shall update.
Matplotlib library of Python is a plotting tool used to plot graphs of functions or figures. It can also be used as an animation tool too. The plotted graphs when added with animations gives a more powerful visualization and helps the presenter to catch a larger number of audience.
Matplotlib can be used to create histograms. A histogram shows the frequency on the vertical axis and the horizontal axis is another dimension. Usually it has bins, where every bin has a minimum and maximum value. Each bin also has a frequency between x and infinite.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With