You need to enable JavaScript to run this app. 如何基于gapminder数据集按大洲分组绘制年份与预期寿命折线图
优惠活动
大模型
产品
解决方案
定价
更多

如何基于gapminder数据集按大洲分组绘制年份与预期寿命折线图

实现方案

你可以根据实际需要选择以下两种常见实现:

方案1:每个大洲对应独立子图,子图内展示该大洲所有国家的预期寿命随年份变化折线

import matplotlib.pyplot as plt

# 获取所有唯一大洲
continents = gapminder['continent'].unique()
# 生成1行5列的子图,可根据需求调整行列布局、画布尺寸
fig, axes = plt.subplots(nrows=1, ncols=len(continents), figsize=(22, 4), sharey=True)

def plot_continent_subgraph(group_df, x_col, y_col, ax):
    # 遍历当前大洲下的所有国家绘制折线
    for _, country_df in group_df.groupby('country'):
        ax.plot(country_df[x_col], country_df[y_col], linewidth=0.7, alpha=0.6)
    ax.set_title(group_df.name, fontsize=12)
    ax.set_xlabel('年份', fontsize=10)
    ax.set_ylabel('预期寿命', fontsize=10)

# 按大洲分组,逐个传入对应子图绘制
for idx, (continent, cont_df) in enumerate(gapminder.groupby('continent')):
    plot_continent_subgraph(cont_df, 'year', 'lifeExp', axes[idx])

plt.tight_layout()
plt.show()

方案2:同一画布展示,不同大洲对应不同颜色的平均预期寿命折线

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 6))
# 先按年份+大洲分组,计算每年各洲的平均预期寿命
cont_yearly_avg = gapminder.groupby(['year', 'continent'])['lifeExp'].mean().reset_index()

def plot_continent_avg_line(group_df, x_col, y_col, **kwargs):
    ax.plot(group_df[x_col], group_df[y_col], label=group_df.name, linewidth=2, **kwargs)

# 按大洲分组绘制折线
cont_yearly_avg.groupby('continent').apply(plot_continent_avg_line, 'year', 'lifeExp')

ax.legend(title='大洲')
ax.set_xlabel('年份', fontsize=11)
ax.set_ylabel('平均预期寿命', fontsize=11)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 01:27:02