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

如何用Matplotlib绘制Pandas DataFrame中垂直存储的多组数据曲线?

使用Matplotlib叠加绘制分组的x-y1和x-y2曲线

没问题,这种把多组数据垂直存储的情况,用Matplotlib叠加绘制曲线其实很简单,我给你完整的实现方案,再拆解细节帮你理解:

完整代码示例

首先我们先还原你的示例数据,然后完成绘图:

import pandas as pd
import matplotlib.pyplot as plt

# 构造你提供的示例DataFrame
data = {
    'curve_number': [1, 1, 1, 1, 2, 2, 2, 2, 3],
    'x': [0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5],
    'y1': [3, 5, 4, 3, 5, 3, 8, 9, 2],
    'y2': [2, 6, 3, 7, 8, 7, 3, 1, 2]
}
df = pd.DataFrame(data)

# 创建绘图画布
plt.figure(figsize=(8, 6))

# 按curve_number分组,遍历每个分组绘制曲线
for curve_id, group_data in df.groupby('curve_number'):
    # 绘制当前分组的x-y1曲线,用圆圈标记,添加图例标签
    plt.plot(group_data['x'], group_data['y1'], marker='o', linewidth=2, label=f'Curve {curve_id} - y1')
    # 绘制当前分组的x-y2曲线,用方块标记,添加图例标签
    plt.plot(group_data['x'], group_data['y2'], marker='s', linewidth=2, label=f'Curve {curve_id} - y2')

# 添加图表基础元素,提升可读性
plt.xlabel('X Axis', fontsize=12)
plt.ylabel('Y Axis', fontsize=12)
plt.title('Overlayed Curves by Curve Number', fontsize=14)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')  # 把图例放在图表外侧,避免遮挡曲线
plt.grid(alpha=0.3)  # 添加半透明网格

# 显示图表
plt.tight_layout()  # 自动调整布局,防止元素被截断
plt.show()

关键步骤解释

  1. 数据分组:用df.groupby('curve_number')把数据按曲线编号拆分,每个分组对应一组完整的x、y1、y2数据,完美匹配你垂直存储的结构。
  2. 循环绘制:遍历每个分组时,分别绘制该组的x-y1和x-y2曲线,用不同的标记(marker='o'和marker='s')区分y1和y2,同时给每条曲线设置明确的图例标签,方便后续区分。
  3. 图表美化:添加坐标轴标签、标题、网格,并且把图例放在图表外侧,避免遮挡曲线,让最终的图表更清晰易读。

可选自定义技巧

  • 区分色系:如果想给不同curve_number的曲线用不同色系,可以用Matplotlib的颜色映射:
    cmap = plt.get_cmap('tab10')  # 选择一个预设色系
    total_curves = df['curve_number'].nunique()
    for curve_id, group_data in df.groupby('curve_number'):
        color = cmap((curve_id - 1) / total_curves)  # 按曲线编号分配颜色
        plt.plot(group_data['x'], group_data['y1'], marker='o', color=color, label=f'Curve {curve_id} - y1')
        plt.plot(group_data['x'], group_data['y2'], marker='s', color=color, linestyle='--', label=f'Curve {curve_id} - y2')
    
    这样同一编号的y1和y2曲线会用同色系,y2用虚线区分,视觉上更统一。
  • 处理不完整数据:像示例中curve 3只有一个数据点,Matplotlib会自动渲染成单个标记,不会影响其他完整曲线的绘制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:09:06