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

如何根据日期条件设置Matplotlib折线图的颜色

按季节为时间序列折线图设置不同颜色

步骤1:预处理数据,添加季节标签

先把日期列转换为datetime类型,再根据月份映射对应季节,同时生成连续同季节的分组标识,用于后续分段绘制折线。

import pandas as pd
import matplotlib.pyplot as plt

# 转换日期列并按时间排序
df['Date Of Experience'] = pd.to_datetime(df['Date Of Experience'])
df = df.sort_values('Date Of Experience')

# 定义季节映射规则
def get_season(month):
    if month in [12, 1, 2]:
        return 'Winter'
    elif month in [3, 4, 5]:
        return 'Spring'
    elif month in [6, 7, 8]:
        return 'Summer'
    else:
        return 'Fall'

# 添加季节列和连续分组列
df['Season'] = df['Date Of Experience'].dt.month.apply(get_season)
df['season_group'] = (df['Season'] != df['Season'].shift()).cumsum()

# 自定义季节-颜色对应表
season_color_map = {
    'Winter': '#1f77b4',
    'Spring': '#2ca02c',
    'Summer': '#ff7f0e',
    'Fall': '#d62728'
}

步骤2:分段绘制折线图

遍历每个连续的同季节数据组,用对应颜色绘制折线,实现跨季节时自动切换颜色的效果。

plt.figure(figsize=(25, 12), dpi=80)

# 遍历分组绘制折线
for _, group in df.groupby('season_group'):
    current_season = group['Season'].iloc[0]
    # 绘制折线
    plt.plot(group['Date Of Experience'], group['Number of reviews'],
             color=season_color_map[current_season], linewidth=2)
    # 可选:添加数据点标记,增强可读性
    plt.scatter(group['Date Of Experience'], group['Number of reviews'],
                color=season_color_map[current_season], s=60, alpha=0.8)

# 设置X轴刻度(沿用你原有的逻辑,改用处理后的日期列)
xtick_positions = df['Date Of Experience'].tolist()[::12]
xtick_labels = [date.strftime('%Y-%m') for date in xtick_positions]
plt.xticks(ticks=xtick_positions, labels=xtick_labels, rotation=90,
           fontsize=12, horizontalalignment='center', alpha=0.7)

# 添加图例、标题和坐标轴标签
from matplotlib.patches import Patch
legend_items = [Patch(facecolor=color, label=season) 
                for season, color in season_color_map.items()]
plt.legend(handles=legend_items, fontsize=14)

plt.title('Number of Reviews by Season', fontsize=18)
plt.ylabel('Number of Reviews', fontsize=14)
plt.xlabel('Date of Experience', fontsize=14)
plt.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.show()

关键说明

  • season_group列用于将连续的同季节数据归为一组,避免折线在非季节分界点无故断开
  • 可以直接修改season_color_map中的颜色值,自定义各季节的显示色调
  • 若不需要数据点标记,可删除plt.scatter()相关代码

内容的提问来源于stack exchange,提问作者Alberto De Benedittis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:31:05