【发布时间】: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
谢谢!
【问题讨论】:
-
这些数据是否在某处可用,以便我们可以使用它?
-
你好汤姆,我已经用我的新代码更新了帖子。这是数据:github.com/abdennouraissaoui/Animated-bubble-chart
标签: python python-3.x matplotlib animation seaborn