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

如何在Python绘图中标注两条曲线的最大/最小温差及对应X值

在Matplotlib中标注两条温度曲线的最大/最小温差及对应时间位置

核心实现步骤

  • 计算目标曲线的温差数组:直接对两条温度数组做差(如delta_temp = temp_a - temp_b)
  • 定位极值点:用numpy的argmax()和argmin()获取最大、最小温差对应的索引
  • 获取对应时间:通过索引从时间数组中提取对应时刻
  • 标注到图表:用Matplotlib的annotate()方法添加带箭头的标注,明确显示温差数值和对应时间

代码示例(基于已有绘图逻辑扩展)

假设你已有基础数据和绘图代码,以下是扩展后的完整实现:

import matplotlib.pyplot as plt
import numpy as np

# 模拟数据:时间(小时)和三条温度曲线
times = np.arange(0, 24, 1)
temp1 = 20 + 5 * np.sin(times * np.pi / 12)
temp2 = 18 + 3 * np.sin(times * np.pi / 12 + 1)
temp3 = 22 + 4 * np.sin(times * np.pi / 12 - 0.5)

# 基础绘图:三条曲线+填充temp1与temp2的差值区域
plt.plot(times, temp1, label='Temp 1')
plt.plot(times, temp2, label='Temp 2')
plt.plot(times, temp3, label='Temp 3')
plt.fill_between(times, temp1, temp2, color='gray', alpha=0.3, label='Temp1-Temp2 ΔT')
plt.xlabel('时间 (h)')
plt.ylabel('温度 (℃)')
plt.legend()

# ---------------------- 温差标注逻辑 ----------------------
# 计算temp1与temp2的温差
delta_temp = temp1 - temp2

# 获取最大温差及对应时间
max_delta_val = np.max(delta_temp)
max_delta_idx = np.argmax(delta_temp)
max_delta_time = times[max_delta_idx]

# 获取最小温差及对应时间
min_delta_val = np.min(delta_temp)
min_delta_idx = np.argmin(delta_temp)
min_delta_time = times[min_delta_idx]

# 标注最大温差:箭头指向两条曲线中点,文本显示详情
plt.annotate(f'ΔT最大值: {max_delta_val:.1f}℃\n时间: {max_delta_time}h',
             xy=(max_delta_time, (temp1[max_delta_idx] + temp2[max_delta_idx])/2),
             xytext=(max_delta_time + 2, (temp1[max_delta_idx] + temp2[max_delta_idx])/2 + 2),
             arrowprops=dict(facecolor='red', shrink=0.05))

# 标注最小温差:根据布局调整文本偏移位置
plt.annotate(f'ΔT最小值: {min_delta_val:.1f}℃\n时间: {min_delta_time}h',
             xy=(min_delta_time, (temp1[min_delta_idx] + temp2[min_delta_idx])/2),
             xytext=(min_delta_time - 6, (temp1[min_delta_idx] + temp2[min_delta_idx])/2 - 3),
             arrowprops=dict(facecolor='blue', shrink=0.05))

plt.show()

关键细节说明

  • 若时间是字符串格式(如['00:00', '01:00', ...]),只需保证索引对应即可,无需修改核心逻辑
  • xy参数设置箭头指向的坐标,选两条曲线中点能更直观展示差值的位置
  • xytext可根据图表布局灵活调整,避免标注遮挡曲线
  • 用.1f格式化温差数值,平衡显示精度和可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 05:36:12