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

如何用Matplotlib基于DataFrame颜色列绘制多色折线?

用LineCollection绘制按列指定颜色的连续折线

解决方案步骤

  1. 准备数据与依赖库
    先导入所需库并创建示例DataFrame:

    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    from matplotlib.patches import Patch
    
    # 构建目标DataFrame
    data = {
        'X': [1,2,3,4,5,6,7,8],
        'Y': [2,1,4,3,1,5,6,8],
        'C': ['R','R','B','R','R','G','G','B']
    }
    df = pd.DataFrame(data)
    
  2. 定义颜色映射
    将C列的标识转换为Matplotlib支持的颜色值:

    color_mapping = {'R': 'red', 'G': 'green', 'B': 'blue'}
    
  3. 生成线段集合
    把坐标点转换为相邻点对组成的线段,这是LineCollection的核心输入:

    # 提取坐标并转为numpy数组
    points = df[['X', 'Y']].to_numpy()
    # 生成相邻点对的线段列表
    segments = [points[i:i+2] for i in range(len(points)-1)]
    
  4. 匹配线段颜色
    为每条线段分配对应起始点的颜色(也可根据需求改为终点颜色):

    colors = df['C'][:-1].map(color_mapping).tolist()
    
  5. 绘制多色折线
    创建LineCollection对象并添加到画布,同时完善图表细节:

    fig, ax = plt.subplots(figsize=(8, 5))
    # 创建线段集合并设置样式
    line_collection = LineCollection(segments, colors=colors, linewidths=2)
    ax.add_collection(line_collection)
    
    # 自动适配坐标轴范围并留边距
    ax.autoscale()
    ax.margins(0.1)
    
    # 添加自定义图例
    legend_elements = [
        Patch(facecolor=color_mapping['R'], label='R'),
        Patch(facecolor=color_mapping['G'], label='G'),
        Patch(facecolor=color_mapping['B'], label='B')
    ]
    ax.legend(handles=legend_elements, loc='upper left')
    
    # 设置坐标轴标签
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    plt.show()
    

优势说明

  • 无折线间断:所有相邻点之间的线段都会被绘制,包括颜色切换的位置
  • 性能更优:仅需一次渲染线段集合,避免了多次分组plot的开销,适合大数据量场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:53:03