【问题标题】:Animating a Seaborn bubble chart using FuncAnimation使用 FuncAnimation 为 Seaborn 气泡图制作动画
【发布时间】:2020-07-19 18:15:02
【问题描述】:

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

我想制作一个动画图表,显示预期寿命和收入如何随时间变化(从 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

谢谢!

【问题讨论】:

标签: python python-3.x matplotlib animation seaborn


【解决方案1】:

您可以通过i 计数器循环多年的数据,该计数器在每个循环(每帧)增加 1。您可以定义一个依赖于iyear 变量,然后通过此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()

再现这个动画:

(我剪了上面的动画是为了文件更轻,小于2MB,实际上数据以5年为增量。但是上面的代码再现了完整的动画,以1年为增量)

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 2015-05-06
    • 2021-02-28
    • 2014-11-20
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多