基于月份分组累计求和的DataFrame绘制多折线图技术问询
绘制按月分组的累计值折线图
没问题!针对你已经处理好的累计值DataFrame,要画出12条分别对应每个月份的折线图,用pandas结合matplotlib或者seaborn就能轻松搞定。我给你两种常用的实现方式,你可以根据自己的偏好选择:
先确认数据结构
首先要确保你的DataFrame里除了months和累计后的value,还有一个用来表示组内顺序的列(比如当月的日期day、或者记录的序号seq)——毕竟折线图需要x轴来体现累计值的变化趋势嘛。假设你的DataFrame结构大概是这样:
| months | seq | value |
|---|---|---|
| 1 | 1 | 10 |
| 1 | 2 | 25 |
| 2 | 1 | 15 |
| ... | ... | ... |
方法1:用Seaborn快速实现(推荐)
Seaborn的lineplot可以直接按hue参数分组绘制多条折线,代码简洁易读:
import seaborn as sns import matplotlib.pyplot as plt # 设置绘图风格 sns.set_style("whitegrid") # 绘制分组折线图:x是组内顺序列,y是累计值,hue按月份分组 sns.lineplot(data=df, x="seq", y="value", hue="months", marker="o") # 添加标题和标签 plt.title("Monthly Cumulative Value Trend", fontsize=14) plt.xlabel("Record Sequence", fontsize=12) plt.ylabel("Cumulative Value", fontsize=12) # 调整图例位置,避免遮挡图表 plt.legend(title="Month", bbox_to_anchor=(1.05, 1), loc="upper left") plt.tight_layout() plt.show()
方法2:用Matplotlib手动循环绘制
如果你更习惯手动控制每个折线的样式,可以用循环遍历每个月份来绘制:
import matplotlib.pyplot as plt # 创建画布 plt.figure(figsize=(10,6)) # 遍历每个月份,绘制对应的折线 for month in df["months"].unique(): # 筛选当前月份的数据 month_data = df[df["months"] == month] # 绘制折线,添加标签 plt.plot(month_data["seq"], month_data["value"], marker="o", label=f"Month {month}") # 添加标题、标签和图例 plt.title("Monthly Cumulative Value Trend", fontsize=14) plt.xlabel("Record Sequence", fontsize=12) plt.ylabel("Cumulative Value", fontsize=12) plt.legend(title="Month", bbox_to_anchor=(1.05, 1), loc="upper left") plt.grid(True) plt.tight_layout() plt.show()
小提示
- 如果你的x轴是日期格式(比如
date列),直接把x="seq"换成x="date"就行,matplotlib会自动处理日期刻度。 - 要是想让不同月份的折线颜色区分更明显,可以自定义颜色列表,传给
palette参数(Seaborn)或者color参数(Matplotlib)。
内容的提问来源于stack exchange,提问作者dps
相关产品推荐
相关产品推荐

