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

Python中基于DataFrame绘制含最值的散点+类errorbar样式图表

解决方案

准备数据

先将你的数据转换为Pandas DataFrame,并把timestamp列转为时间类型:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    'timestamp': ['2021-08-11 04:05:06', '2021-08-11 04:15:06', '2021-08-11 09:15:26',
                  '2021-08-11 11:04:06', '2021-08-11 14:55:16', '2021-08-13 04:12:11'],
    'average': [2.0, 2.3, 2.5, 2.3, 2.6, 2.1],
    'min': [1.8, 2.0, 2.3, 2.1, 2.2, 1.7],
    'max': [2.2, 2.7, 2.8, 2.6, 2.9, 2.3]
}

df = pd.DataFrame(data)
df['timestamp'] = pd.to_datetime(df['timestamp'])

方案1:无误差棒样式(对应Fig.1)

实现散点图展示average,虚线绘制min/max,并分别填充指定颜色的区域:

plt.figure(figsize=(10, 6))

# 填充average与max之间的浅红色区域
plt.fill_between(df['timestamp'], df['average'], df['max'], color='lightcoral', alpha=0.3)
# 填充average与min之间的浅蓝色区域
plt.fill_between(df['timestamp'], df['average'], df['min'], color='lightblue', alpha=0.3)

# 绘制min和max的虚线
plt.plot(df['timestamp'], df['min'], linestyle='--', color='darkblue', label='min')
plt.plot(df['timestamp'], df['max'], linestyle='--', color='darkred', label='max')

# 绘制average的散点
plt.scatter(df['timestamp'], df['average'], color='black', s=50, label='average')

# 图表美化
plt.xlabel('Timestamp')
plt.ylabel('Value')
plt.title('Average with Min-Max Fill')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
  • fill_between负责填充区域,alpha参数调整透明度避免遮挡底层元素
  • 通过linestyle='--'设置虚线样式,散点用scatter实现

方案2:带误差棒样式(对应Fig.2)

利用errorbar实现误差棒效果,同时保留min/max的虚线:

plt.figure(figsize=(10, 6))

# 计算上下误差范围:下方为average-min,上方为max-average
upper_err = df['max'] - df['average']
lower_err = df['average'] - df['min']

# 绘制带误差棒的均值点
plt.errorbar(df['timestamp'], df['average'], yerr=[lower_err, upper_err], 
             fmt='o', color='black', ecolor='gray', capsize=5, label='average')

# 叠加min和max的虚线
plt.plot(df['timestamp'], df['min'], linestyle='--', color='darkblue', label='min')
plt.plot(df['timestamp'], df['max'], linestyle='--', color='darkred', label='max')

# 图表美化
plt.xlabel('Timestamp')
plt.ylabel('Value')
plt.title('Average with Min-Max Error Bars')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
  • yerr参数需传入上下两组误差数据,capsize控制误差棒两端短帽的长度
  • fmt='o'设置均值点为圆形,同时保留min/max虚线以匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:17:25