我有一个数据集,其中包含了不同时期每个国家的收入和预期寿命。在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
谢谢大家!
您可以通过
i
计数器循环数年的数据,每个循环(每帧)增加1。您可以定义一个year
变量,该变量依赖于i
,然后通过该year
过滤数据并绘制过滤后的数据帧。在每个循环中,您必须用ax.cla()
擦除上一个散点图。最后,我选择了220帧,以便从1800年到2019年每年都有一个帧。选中此代码作为参考:
将复制此动画:
(我剪切上面的动画是为了有一个更轻的文件,小于2MB,事实上数据以5年的步长增加。但是上面的代码以1年的步长复制完整的动画)
相关问题 更多 >
编程相关推荐