You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Matplotlib实现随年份变化的气泡图动画?

解决气泡图动画年份数据重叠问题

你的代码核心问题是每次动画帧都绘制了全量数据集,没有按年份筛选数据,导致所有年份的点重叠显示。以下是修复后的完整代码:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# 先提取数据集里去重的年份列表,确保和动画帧数量匹配
year_list = sorted(df['year'].unique())

fig, ax = plt.subplots()

def animate_(i):
    # 清空当前轴内容
    ax.clear()
    
    # 筛选当前帧对应的年份数据
    current_year = year_list[i]
    df_year = df[df['year'] == current_year]
    
    # 绘制当前年份的气泡图
    s = ax.scatter("LifeExpectency",
                   "GDP_in_log2",
                   alpha=0.5,
                   s='population',  # 若人口数值过大,建议缩放,比如s=df_year['population']/10000
                   c='colorForContinent',
                   data=df_year)
    
    # 固定坐标轴范围,避免帧间坐标轴跳动(数值根据你的数据调整)
    ax.set_xlim(df['LifeExpectency'].min() - 5, df['LifeExpectency'].max() + 5)
    ax.set_ylim(df['GDP_in_log2'].min() - 1, df['GDP_in_log2'].max() + 1)
    
    # 添加年份标注,明确当前显示的年份
    ax.text(0.85, 0.95, str(current_year), transform=ax.transAxes, 
            fontsize=12, bbox=dict(facecolor='white', alpha=0.8))
    
    # 设置轴标签
    ax.set_xlabel('Life Expectancy')
    ax.set_ylabel('GDP (log2)')
    
    return s,

# 用年份列表长度作为帧数量,确保每个年份对应一帧
anim = FuncAnimation(fig, animate_, frames=len(year_list), interval=500, blit=False)

# 保存动画(可选,需安装ffmpeg)
# anim.save('Countries progression.mp4', writer='ffmpeg')
plt.show()

关键修改说明:

  • 按年份筛选数据:通过year_list[i]定位当前帧对应的年份,从原数据集中过滤出该年份的记录,确保每帧只显示当年数据
  • 固定坐标轴范围:避免因不同年份数据分布差异导致坐标轴频繁变动,提升动画观看连贯性
  • 添加年份标注:在图中显眼位置显示当前年份,让观众清晰了解动画进度
  • 匹配帧与年份数量:用年份列表的长度作为frames参数,确保每个年份都对应一帧

内容的提问来源于stack exchange,提问作者viththi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:00:59