繁体   English   中英

使用 FuncAnimation 为 Seaborn 气泡图制作动画

[英]Animating a Seaborn bubble chart using FuncAnimation

我有一个数据集,其中包含每个国家/地区的收入和预期寿命。 在 1800 年,它看起来像这样:1

我想制作一个动画图表,显示预期寿命和收入如何随时间变化(从 1800 年到 2019 年)。 到目前为止,这是我的 static plot 的代码:

import matplotlib
fig, ax = plt.subplots(figsize=(12, 7))

chart = sns.scatterplot(x="Income",
                        y="Life Expectancy",
                        size="Population",
                        data=gapminder_df[gapminder_df["Year"]==1800],
                        hue="Region", 
                        ax=ax,
                        alpha=.7,
                        sizes=(50, 3000)
                       )

ax.set_xscale('log')
ax.set_ylim(25, 90)
ax.set_xlim(100, 100000)

scatters = [c for c in ax.collections if isinstance(c, matplotlib.collections.PathCollection)]

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:5], labels[:5])

def animate(i):
    data = gapminder_df[gapminder_df["Year"]==i+1800]
    for c in scatters:
        # do whatever do get the new data to plot
        x = data["Income"]
        y = data["Life Expectancy"]
        xy = np.hstack([x,y])
        # update PathCollection offsets
        c.set_offsets(xy)
        c.set_sizes(data["Population"])
        c.set_array(data["Region"])
    return scatters

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=10, blit=True)
ani.save("test.mp4")

这是数据的链接: https://github.com/abdennouraissaoui/Animated-bubble-chart

谢谢!

您可以通过i计数器循环多年的数据,该计数器在每个循环(每帧)增加 1。 您可以定义一个取决于iyear变量,然后按year过滤您的数据,并过滤 plot 过滤后的 dataframe。 在每个循环中,您必须使用ax.cla()擦除前一个散点图。 最后,我选择了 220 帧,以便每年都有一个帧,从 1800 年到 2019 年。
检查此代码作为参考:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.animation import FuncAnimation

gapminder_df = pd.read_csv('data.csv')

fig, ax = plt.subplots(figsize = (12, 7))

def animate(i):
    ax.cla()
    year = 1800 + i
    sns.scatterplot(x = 'Income',
                    y = 'Life Expectancy',
                    size = 'Population',
                    data = gapminder_df[gapminder_df['Year'] == year],
                    hue = 'Region',
                    ax = ax,
                    alpha = 0.7,
                    sizes = (50, 3000))
    ax.set_title(f'Year {year}')
    ax.set_xscale('log')
    ax.set_ylim(25, 90)
    ax.set_xlim(100, 100000)
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[:5], labels[:5], loc = 'upper left')

ani = FuncAnimation(fig = fig, func = animate, frames = 220, interval = 100)
plt.show()

重现此 animation:

在此处输入图像描述

(我把上面的 animation 剪掉了,为了有一个更轻的文件,小于 2 MB,实际上数据以 5 年为增量增加。但是上面的代码复制了完整的 animation,以 1 年为增量)

暂无
暂无

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

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