使用FuncAnimation设置Seaborn气泡图的动画

2024-09-29 01:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,其中包含了不同时期每个国家的收入和预期寿命。在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

谢谢大家!


Tags: 数据dfdatalabelsmatplotlibchartfigax
1条回答
网友
1楼 · 发布于 2024-09-29 01:19:11

您可以通过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年的步长复制完整的动画)

相关问题 更多 >