Reputation: 137
I am learning matplotlib for my needs. In the example from the matplotlib site, I found an animated histogram graph. I'm getting a batch of data that I'm displaying with a histogram, but I would like the graph to continue to the right each time the animate function is called, instead of redrawing the old one. The rendered frames should remain in place and should not move. You should get a history of the received data. Example
Code from example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Fixing random state for reproducibility
np.random.seed(19680801)
# Fixing bin edges
HIST_BINS = np.linspace(-4, 4, 100)
# histogram our data with numpy
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
def prepare_animation(bar_container):
def animate(frame_number):
# simulate new data coming in
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
for count, rect in zip(n, bar_container.patches):
rect.set_height(count)
return bar_container.patches
return animate
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1,
ec="yellow", fc="green", alpha=0.5)
ax.set_ylim(top=55) # set safe limit to ensure that all data is visible.
ani = animation.FuncAnimation(fig, prepare_animation(bar_container), 50,
repeat=False, blit=True)
plt.show()
Upvotes: 1
Views: 76
Reputation: 37787
You're two lines away from your expected output.
To make sure the plot gonna be shifted to the right each time you call animate
, you need to make sure that the xlim
(which is the view limit of the x-axis) gets increased in //. To do that, you can use Axes.set_xlim
:
def animate(frame_number):
# simulate new data coming in
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
for count, rect in zip(n, bar_container.patches):
rect.set_height(count)
rect.set_x(rect.get_x() + 1) # <- add this line
ax.set_xlim(ax.get_xlim()[0], ax.get_xlim()[1] + 1) # <- add this line
return bar_container.patches
return animate
Output (plot/animation) :
Upvotes: 1