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

如何在Matplotlib中为同类传感器测量值绘制相近色系曲线?

在Matplotlib中实现同传感器数据同色系多组区分的简便方法

你可以直接利用Matplotlib内置的色系colormap来实现需求,不用手动自定义色表,步骤如下:

核心思路

给每个传感器分配一个对应色系的内置colormap(比如Sensor A用蓝系Blues、Sensor B用黄系YlOrBr、Sensor C用红系Reds),然后从每个colormap中按测量组数均匀提取不同深浅的颜色,这样同传感器的多组数据会保持同色系但有明显深浅区分。

代码实现示例

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# 加载你的测量数据(这里用示例数据模拟)
measurements = [
    pd.DataFrame({
        '时间': ['0 h', '1 h', '2 h'],
        'Sensor A': [20, 21, 20],
        'Sensor B': [18, 19, 19],
        'Sensor C': [16, 16, 17]
    }),
    pd.DataFrame({
        '时间': ['0 h', '1 h', '2 h'],
        'Sensor A': [19, 21, 20],
        'Sensor B': [19, 18, 19],
        'Sensor C': [15, 16, 14]
    }),
    pd.DataFrame({
        '时间': ['0 h', '1 h', '2 h'],
        'Sensor A': [21, 22, 20],
        'Sensor B': [18, 19, 19],
        'Sensor C': [16, 16, 17]
    })
]

# 绑定传感器与对应色系colormap
sensor_cmap_map = {
    'Sensor A': plt.cm.Blues,
    'Sensor B': plt.cm.YlOrBr,
    'Sensor C': plt.cm.Reds
}
num_groups = len(measurements)

# 为每个传感器生成对应组数的颜色(取colormap中间段,避免极端色)
sensor_colors = {
    sensor: cmap(np.linspace(0.3, 0.8, num_groups))
    for sensor, cmap in sensor_cmap_map.items()
}

# 绘图
plt.figure(figsize=(10, 6))
time_indices = np.arange(len(measurements[0]['时间']))  # 转换时间为数字索引方便绘图

for group_idx, df in enumerate(measurements):
    for sensor in ['Sensor A', 'Sensor B', 'Sensor C']:
        plt.plot(time_indices, df[sensor], color=sensor_colors[sensor][group_idx],
                 label=f'{sensor} 测量{group_idx+1}')

# 设置坐标轴与图例
plt.xticks(time_indices, measurements[0]['时间'])
plt.xlabel('时间')
plt.ylabel('温度 (°C)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()

关键细节说明

  • 选择内置colormap:Blues/YlOrBr/Reds都是Matplotlib原生的连续色系,完美匹配你的颜色需求
  • 颜色取值范围:用np.linspace(0.3, 0.8)避开colormap最浅(接近白色)和最深(接近黑色)的部分,保证同色系内的区分度,同时避免不同色系间的颜色重叠
  • 灵活性:如果后续增加测量组数,只需要调整num_groups,颜色会自动均匀生成

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:40:31