简体   繁体   English

Matplotlib对箱形图进行动画处理

[英]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: 我正在研究matplotlib动画示例,该示例显示了它如何与plot函数一起工作,但是对于boxplot函数来说似乎没有什么用:

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. Boxplot似乎也没有“ set_data”功能或“ animated = True”参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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