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

Python实现:在对数刻度热力图上叠加曲线的方法

实现热力图叠加曲线(含对数刻度)

核心思路

  • 用seaborn.heatmap绘制热力图,通过LogNorm实现颜色的对数刻度映射
  • 将曲线的日期转换为热力图x轴的对应位置,确保曲线与热力图坐标对齐
  • 在同一轴上叠加曲线,调整样式区分图层

完整代码实现

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

# 生成你提供的DataFrame
data_flexibilities = {
    'power': [-1, 0, 1, 2, 3],
    '2022-06-01T02:00:00+00:00': [1, 7, 9, 10, 5],
    '2022-06-01T03:00:00+00:00': [6, 7, 1, 4, 5],
    '2022-06-01T05:00:00+00:00': [8, 5, 3, 7, 8],
}
all_flexibilities = pd.DataFrame(data_flexibilities)
all_flexibilities.set_index('power', inplace=True)
all_flexibilities.columns = pd.to_datetime(all_flexibilities.columns)

data_curve = {
    'dates': ['2022-06-01T02:00:00+00:00', '2022-06-01T03:00:00+00:00', '2022-06-01T5:00:00+00:00'],
    'power_consumption': [0, 2, 2]
}
curve_to_plot = pd.DataFrame(data_curve)
curve_to_plot['dates'] = pd.to_datetime(curve_to_plot['dates'])

# 1. 绘制热力图
plt.figure(figsize=(10, 6))
# 使用LogNorm实现颜色的对数刻度
ax = sns.heatmap(all_flexibilities, 
                 cmap='viridis', 
                 norm=LogNorm(vmin=all_flexibilities.min().min(), vmax=all_flexibilities.max().max()),
                 xticklabels=[col.strftime('%Y-%m-%d %H:%M') for col in all_flexibilities.columns],
                 yticklabels=all_flexibilities.index)

# 2. 处理曲线的坐标对齐
# 获取每个日期在热力图x轴的位置(列索引)
x_positions = [all_flexibilities.columns.get_loc(date) for date in curve_to_plot['dates']]
y_values = curve_to_plot['power_consumption']

# 3. 叠加曲线
ax.plot(x_positions, y_values, color='red', marker='o', linewidth=2, label='Power Consumption')

# 调整样式
ax.set_xlabel('Date')
ax.set_ylabel('Power')
ax.set_title('Heatmap with Power Consumption Curve')
ax.legend()

plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

关键细节说明

  • 对数刻度实现:通过LogNorm类对热力图的颜色值做对数转换,适配数据的对数特性,避免小值被大值覆盖
  • 坐标对齐:热力图的x轴本质是列的索引位置(0,1,2...),而非实际日期,因此需要用get_loc方法将日期转换为对应位置,确保曲线与热力图的x轴对齐
  • 样式区分:用醒目的颜色(如红色)和标记点绘制曲线,与热力图形成视觉区分,添加图例增强可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:28:14