Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib Animate a box plot

I'm trying to animate a box plot as data shifts over a time series.

I'm working off the matplotlib animate examples, which show how it works with the plot function, but that doesn't seem to carry over for a boxplot function:

Code Works below, but changing the two lines to box plot gives me errors

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
line, = ax.plot(np.arange(10))  # <-- ax.boxplot(np.arange(10))
ax.set_ylim(0, 20)


def update(data):
    line.set_ydata(data)  # < -- line = ax.boxplot(data)? 
    return line,


def data_gen():
    i = 0
    while True:
        yield np.arange(10) + i
        i += .1

ani = animation.FuncAnimation(fig, update, data_gen, interval=100)
plt.show()

Boxplot also doesn't seem to have a "set_data" function, or an "animated=True" parameter.

Essentially I'd like the animation to work the same as above, but depicting a box plot instead of a line plot.

like image 850
Joshua Zastrow Avatar asked Sep 20 '26 01:09

Joshua Zastrow


1 Answers

I figured it out myself: The idea can be to clear the axes, and in each frame draw a new boxplot as shown below.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
# line, = ax.boxplot(np.arange(10))  <-- not needed it seems
ax.set_ylim(0, 20)


def update(data):
    ax.cla()  # <-- clear the subplot otherwise boxplot shows previous frame
    ax.set_ylim(0, 20)
    ax.boxplot(x=data)  


def data_gen():
    i = 0
    while True:
        yield np.arange(10) + i
        i += .1

ani = animation.FuncAnimation(fig, update, data_gen, interval=100)
plt.show()
like image 144
Joshua Zastrow Avatar answered Sep 21 '26 14:09

Joshua Zastrow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!