Python 使用FuncAnimation设置Seaborn气泡图的动画
我有一个数据集,其中包含了不同时期每个国家的收入和预期寿命。在1800年,它看起来是这样的: 我想制作一张动画图表,展示预期寿命和收入随时间的变化(从1800年到2019年)。 以下是我到目前为止关于静态绘图的代码:Python 使用FuncAnimation设置Seaborn气泡图的动画,python,python-3.x,matplotlib,animation,seaborn,Python,Python 3.x,Matplotlib,Animation,Seaborn,我有一个数据集,其中包含了不同时期每个国家的收入和预期寿命。在1800年,它看起来是这样的: 我想制作一张动画图表,展示预期寿命和收入随时间的变化(从1800年到2019年)。 以下是我到目前为止关于静态绘图的代码: import matplotlib fig, ax = plt.subplots(figsize=(12, 7)) chart = sns.scatterplot(x="Income", y="Lif
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")
以下是数据链接:
谢谢大家! 您可以通过
i
计数器循环多年的数据,每个循环(每帧)增加1。您可以定义一个取决于i
的year
变量,然后根据该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年的步长复制完整的动画)这些数据在什么地方可用,以便我们可以使用它吗?你好,汤姆,我已经用我的新代码更新了帖子。以下是数据: