I am trying to create animation of histogram and a plot together, side-by-side. I learned how to make histogram from here and to do multiple plotting from here.
When I tried to combine the codes together as follows:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
n_frames = 100 #total number of frames
time = [] #x-axis data
mean = [] #y-axis data
def animate(frame_number, bar_container, line):
data = np.random.randn(1000) #generate data
n, _ = np.histogram(data, HIST_BINS) #create histogram
for count, rect in zip(n, bar_container.patches):
rect.set_height(count)
time.append(frame_number)#update x-axis
mean.append(np.mean(data))#update y-axis
line.set_data(time, mean)
return bar_container.patches, line
HIST_BINS = np.linspace(-4, 4, 100)
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_ylim(top=55) # set safe limit to ensure that all data is visible.
ax1.set_ylabel('Count')
ax1.set_xlabel('Lengths')
_, _, bar_container = ax1.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)
line, = ax2.plot([], [])
ax2.set_ylim(-4,4)
ax2.set_xlim(0, n_frames)
ax2.set_ylabel('mean')
ax2.set_xlabel('time')
fig.tight_layout(pad = 1)
ani = animation.FuncAnimation(fig, animate, frames = np.arange(n_frames), fargs = (bar_container,line), blit=True)
plt.show()
The code process 1st frame and then stops with the error:
Traceback (most recent call last):
File "/home/kartik/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 224, in process
func(*args, **kwargs)
File "/home/kartik/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 975, in _start
self._init_draw()
File "/home/kartik/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1719, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "/home/kartik/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1748, in _draw_frame
key=lambda x: x.get_zorder())
File "/home/kartik/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1748, in <lambda>
key=lambda x: x.get_zorder())
AttributeError: 'list' object has no attribute 'get_zorder'
What am I doing wrong and how do I resolve it?
Thanks