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

如何为Pandas groupby结果多列绘图,实现按国家分的销售额趋势子图

问题原因

之前的方案多使用了直方图hist(),这类图表用于展示数据分布,无法呈现销售额随时间的变化趋势,同时绘图时未明确指定x轴为Date字段,因此不符合需求。

可运行解决方案代码
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 示例数据集
data = {'Country': ['Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK', 'Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK', 'Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK'],
        'Date': ['Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020'],
        'Sales': [20000, 30000, 10000, 10000, 30000, 10000, 10000, 50000, 40000, 30000, 20000, 30000, 10000, 10000, 60000, 70000, 80000, 10000, 30000, 10000, 10000]}
df = pd.DataFrame(data)

# 先将Date转为有序分类,保证x轴时间顺序正确,如有其余月份按时间顺序补充到列表中即可
date_order = ['Jan 2020', 'Feb 2020', 'Dec 2020']
df['Date'] = pd.Categorical(df['Date'], categories=date_order, ordered=True)

# 按国家分组
grouped = df.groupby('Country')
# 计算子图行列数
n_cols = 2
n_rows = int(np.ceil(grouped.ngroups / n_cols))
fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, figsize=(10, 12), sharey=False)
axes_flat = axes.flatten()

# 遍历每个国家分组绘图
for idx, (country, group_data) in enumerate(grouped):
    current_ax = axes_flat[idx]
    # 明确指定x、y轴,可根据需要修改kind参数为bar等其他图表类型
    group_data.plot(x='Date', y='Sales', ax=current_ax, kind='line', legend=False, marker='o')
    # 自定义子图标题、轴标签
    current_ax.set_title(f'{country} 2020年销售额变化')
    current_ax.set_xlabel('月份')
    current_ax.set_ylabel('销售额')
    current_ax.grid(alpha=0.3)

# 隐藏多余的空白子图
for empty_ax in axes_flat[grouped.ngroups:]:
    empty_ax.axis('off')

# 调整布局避免标签重叠
plt.tight_layout()
plt.show()
方案说明
  • 明确指定绘图时的x、y轴参数,直接匹配需求的Date和Sales字段
  • 提前处理Date列为有序分类,避免x轴按字符串排序出现时间顺序错乱
  • 循环过程中单独为每个子图配置标题和坐标轴标签,支持完全自定义
  • 自动隐藏多余的空白子图,调整布局避免内容重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:54:07