简体   繁体   中英

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.

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()
# Unset socks proxy unset all_proxy unset ALL_PROXY # Install missing dependencies: pip install pysocks # Reset proxy source ~/.bashrc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM