如何根据分类变量绘制单条多颜色时间序列折线图
解决方案
要实现单条折线按kind分类显示不同颜色的效果,我们需要修改原有代码的绘图逻辑——不再按类别拆分多条折线,而是分段绘制连续线段,让每段线段的颜色对应其左侧数据点的kind类别,同时保留散点标记和图例。
修改后的完整代码
import matplotlib.pyplot as plt def plot_timeseries_by_category(df, category_col): # 获取索引中的唯一年份 years = df.index.year.unique() # 为每个年份创建子图 fig, axes = plt.subplots(len(years), 1, figsize=(10, len(years)*5)) if len(years) == 1: axes = [axes] # 为所有类别统一分配颜色(保持跨年份颜色一致) colors = {category: f'C{index}' for index, category in enumerate(df[category_col].unique())} for year, ax in zip(years, axes): # 筛选当前年份数据并按时间排序(确保绘图顺序正确) df_year = df[df.index.year == year].sort_index() # 按类别绘制散点标记(用于区分数据点并生成图例) for category in colors: mask = df_year[category_col] == category ax.scatter(df_year.index[mask], df_year['dailyp'][mask], color=colors[category], label=category, marker='o') # 分段绘制连接线,线段颜色取左侧点的类别对应颜色 for i in range(len(df_year)-1): # 获取相邻两个点的时间和数值 x_points = [df_year.index[i], df_year.index[i+1]] y_points = [df_year['dailyp'].iloc[i], df_year['dailyp'].iloc[i+1]] # 匹配左侧点的类别颜色 segment_color = colors[df_year[category_col].iloc[i]] # 绘制单段线段 ax.plot(x_points, y_points, color=segment_color) # 设置子图样式 ax.set_title(f'{year} 每日数据按类别着色') ax.legend(title=category_col) ax.tick_params(axis='x', rotation=45) # 旋转日期标签避免重叠 plt.tight_layout() plt.show()
关键修改说明
- 统一颜色映射:将颜色字典的创建移到年份循环外,确保跨年份的同一
kind类别颜色一致。 - 分段绘制线段:遍历相邻数据点,按左侧点的
kind颜色绘制线段,实现单条折线的多色效果。 - 散点标记+图例:通过散点绘制实现类别区分和图例生成(直接绘制线段无法自动生成图例)。
- 数据排序:增加
sort_index()确保数据严格按时间顺序排列,避免线段绘制混乱。
使用方式
直接传入你的DataFrame和类别列名即可调用:
plot_timeseries_by_category(your_dataframe, category_col='kind')
内容的提问来源于stack exchange,提问作者Apollo
相关产品推荐
相关产品推荐

