我有一个Pandas 数据框,它看起来:

d = {'time': [1, 3, 5,7, 9, 11, 13, 15, 17, 19],
     'method1':[0.864231038, 0.874805716, 0.890315836, 0.906831719, 0.91634293, 0.928120905, 0.938231839, 0.947280697,
              0.951635588, 0.951468784],
    'method2':[0.867868393, 0.878908199, 0.893329853, 0.911470465, 0.924099528, 0.934628044, 0.945209861, 0.951776017,
               0.954180089, 0.95553498]} 

df = pd.DataFrame(data=d)
df

输出:

    time    method1 method2
0   1   0.864231    0.867868
1   3   0.874806    0.878908
2   5   0.890316    0.893330
3   7   0.906832    0.911470
4   9   0.916343    0.924100
5   11  0.928121    0.934628
6   13  0.938232    0.945210
7   15  0.947281    0.951776
8   17  0.951636    0.954180
9   19  0.951469    0.955535

我为方法1和方法2绘制了这个数据框,其值列如下所示

x_labels = df['time']
fig, ax = plt.subplots()
ax.set_xlabel('Time', fontsize=14)
ax.set_ylabel('value', fontsize=14)

sns.lineplot(x=x_labels, y=df['method1'], ax=ax, label='method1')
sns.lineplot(x=x_labels, y=df['method2'], ax=ax, label='method2')
plt.xlim(xmin=0)
ax.set_xlim([1, 19])

输出:

enter image description here

但是,我希望通过使用GIF来可视化数据,以下是我的预期输出:

enter image description here

推荐答案

您可以使用matplotlib.animation API.

import matplotlib.animation as animation

下面是一个例子:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

def animate(i):
    ax.clear()
    x_labels = df['time'][:i+1]
    ax.set_xlim([1, 19])
    ax.set_xlabel('Time', fontsize=14)
    ax.set_ylabel('value', fontsize=14)
    sns.lineplot(x=x_labels, y=df['method1'][:i+1], ax=ax, label='method1')
    sns.lineplot(x=x_labels, y=df['method2'][:i+1], ax=ax, label='method2')

anim = animation.FuncAnimation(fig, animate, frames=len(df), interval=500)
anim.save('test.gif')

enter image description here


标准实现是以长形式传递数据帧,而不是宽形式,这允许使用hue参数,并且只有一次Plot调用.但是,这会导致线条被连续绘制,而不是同时绘制.

# convert the dataframe to a long form
df = df.melt(id_vars='time')

fig, ax = plt.subplots()

def animate(i):
    ax.clear()
    data = df.iloc[:i+1, :]  # select rows to i+1 with each frame
    sns.lineplot(data=data, x='time', y='value', ax=ax, hue='variable')
    ax.set_xlabel('Time', fontsize=14)
    ax.set_ylabel('value', fontsize=14)
    ax.set_xlim([1, 19])

anim = animation.FuncAnimation(fig, animate, frames=len(df), interval=500)
anim.save('test.gif')

enter image description here

Python相关问答推荐

Python tkinter关闭第一个窗口,同时打开第二个窗口

如何以实现以下所述的预期行为的方式添加两只Pandas pyramme

使用Curses for Python保存和恢复终端窗口内容

Altair -箱形图边界设置为黑色,中线设置为红色

如何在矩阵上并行化简单循环?

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

Pandas 滚动最接近的价值

难以在Manim中正确定位对象

log 1 p numpy的意外行为

使用@ guardlasses. guardlass和注释的Python继承

计算组中唯一值的数量

如何过滤包含2个指定子字符串的收件箱列名?

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

实现神经网络代码时的TypeError

如何从需要点击/切换的网页中提取表格?

在Python中计算连续天数

在极中解析带有数字和SI前缀的字符串

在输入行运行时停止代码

如何使用使用来自其他列的值的公式更新一个rabrame列?