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

标签 python python-3.x matplotlib animation seaborn

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

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

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。您可以定义一个 year 变量,它取决于 i,然后按此 year 过滤您的数据并绘制过滤后的数据框。在每个循环中,您必须使用 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()

重现此动画:

enter image description here

(我把上面的动画剪掉是为了让文件更轻,不到2MB,实际上数据以5年为步长增长。但是上面的代码再现了完整的动画,以1年为步长)

关于python - 使用 FuncAnimation 为 Seaborn 气泡图制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62983997/

相关文章:

同时监听/响应 HTTP 请求、串行端口和基于时间的事件的 Python 脚本?

Python - 迭代字典并更改字典 - 如何?

python - 手动安装SciPy,NumPy,MatPlotlib(Windows)

python - 在 python 中创建矢量图形以在 word/powerpoint 中使用的最佳方法

matplotlib - jupyter notebook 中的交互式 matplotlib 绘图

python - 将多个 numpy 数组合并为一个

python - 发布 django 时过滤 csrfmiddlewaretoken

python - 不可排序的类型 : int() < Entry()

python - 从绘图 3d 图中抓取相机位置

python - 使用 MySQL 时,Django IntegerField 将 0 作为 None 值检索