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

如何基于分组数据用Pandas绘制多折线图(Python)

实现方法建议

首先你的DataFrame里Manager列存在缺失值(每个经理除首行外,其余行的Manager字段为空),第一步需要填充这些缺失值,确保每条数据都对应正确的经理。然后要设置月份的正确时间顺序,避免绘图时月份按字母乱序排列,最后用可视化库绘制折线图。

步骤1:预处理DataFrame

用ffill()方法向前填充Manager列的空值:

import pandas as pd

# 假设你的DataFrame已加载为manager
manager['Manager'] = manager['Manager'].ffill()

步骤2:设置月份的正确顺序

把Month_name转换成有序的类别型数据,确保绘图时按Jan-Feb-Mar-Apr-May-Jun的时间顺序展示:

month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
manager['Month_name'] = pd.Categorical(manager['Month_name'], categories=month_order, ordered=True)

步骤3:绘制折线图

这里提供两种常用库的实现方式:

方式一:使用Matplotlib

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))

# 遍历每个经理,绘制对应折线
for name, group in manager.groupby('Manager'):
    # 按月份排序后绘图
    sorted_group = group.sort_values('Month_name')
    plt.plot(sorted_group['Month_name'], sorted_group['Sales'], marker='o', label=name)

plt.xlabel('月份')
plt.ylabel('销售额')
plt.title('各经理月度销售额趋势')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

方式二:使用Seaborn(更简洁)

import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
# 用lineplot直接绘制,hue参数区分不同经理
sns.lineplot(data=manager, x='Month_name', y='Sales', hue='Manager', marker='o')

plt.xlabel('月份')
plt.ylabel('销售额')
plt.title('各经理月度销售额趋势')
plt.grid(True, alpha=0.3)
plt.show()

这样绘制出的折线图会符合你的需求:每个经理对应一条折线,x轴按正确的月份顺序排列,清晰展示各经理的月度销售额变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:10:33