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

如何用Pandas和Matplotlib按月份分组DataFrame绘制多折线图?

按支付方式绘制月度数值折线图

需求说明

读取结构如下的CSV文件,为每种支付方式(A/B/C)绘制对应月度数值的折线图,x轴刻度为每个月份:

dates = [["2022-03-31", "A",100], ["2022-03-31", "B",100],  ["2022-03-31", "C", 250], ["2022-04-30", "A", 500], ["2022-04-30", "B", 100], ["2022-04-30", "C", 200], ["2022-05-31", "A",200], ["2022-05-31", "B", 300], ["2022-05-31", "C", 500]]
df = pd.DataFrame(dates, columns=['Dates',"Payment Method", "Values"])
df.to_csv("example.csv",index=False)

注:原示例中2022-04-31为无效日期,已修正为2022-04-30

实现步骤与代码

  1. 读取数据并处理日期:将Dates列转为datetime类型,提取年月格式作为x轴显示刻度
  2. 数据透视重组:把长格式数据转为宽格式,让每个支付方式成为单独列,方便直接绘制折线
  3. 绘制折线图:用matplotlib设置坐标轴、图例等元素

完整代码:

import pandas as pd
import matplotlib.pyplot as plt

# 读取CSV并处理日期
df = pd.read_csv("example.csv")
df['Dates'] = pd.to_datetime(df['Dates'])
# 提取"年-月"格式作为x轴刻度标签
df['Month'] = df['Dates'].dt.strftime('%Y-%m')

# 数据透视:行是月份,列是支付方式,值为对应月度数值
pivot_df = df.pivot(index='Month', columns='Payment Method', values='Values')

# 绘制折线图
plt.figure(figsize=(10, 6))
# 遍历每个支付方式,绘制对应折线
for method in pivot_df.columns:
    plt.plot(pivot_df.index, pivot_df[method], marker='o', label=method)

# 设置图表属性
plt.xlabel('月份')
plt.ylabel('数值')
plt.title('各支付方式月度数值趋势')
plt.legend(title='支付方式')
plt.grid(True, linestyle='--', alpha=0.7)

# 旋转x轴刻度,避免重叠
plt.xticks(rotation=45)

plt.tight_layout()
plt.show()

代码说明

  • pivot方法自动按月份和支付方式分组,确保每个月份下的支付方式数值一一对应
  • dt.strftime('%Y-%m')将日期转为简洁的"年-月"格式,作为清晰的x轴刻度
  • 循环绘制折线时添加标记点,提升数据点的辨识度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:05:22