繁体   English   中英

带有日期时间 x 轴的 Matplotlib/seaborn 热图显示 1970 年,而不是使用 AutoFormatter 的实际日期时间

[英]Matplotlib/seaborn heatmap with a datetime x-axis shows 1970 instead of real datetime with AutoFormatter

我有一个使用以下数据透视表生成的热图:

HCpredictedLabel         B     H      R
datetime                               
2021-07-20 09:00:00  115.0  80.0  119.0
2021-07-20 09:05:00   69.0  38.0  149.0
2021-07-20 09:10:00   58.0  50.0  131.0
2021-07-20 09:15:00   71.0  31.0  162.0
2021-07-20 09:20:00   78.0  38.0  164.0
...                    ...   ...    ...
2021-07-21 07:35:00    3.0  10.0   14.0
2021-07-21 07:40:00    9.0   1.0   30.0
2021-07-21 07:45:00    8.0   3.0   31.0
2021-07-21 07:50:00   12.0  13.0   26.0
2021-07-21 07:55:00   25.0  35.0   97.0

[114 rows x 3 columns]

热图的 x 轴显示日期时间,我希望根据数据集中的范围(可以是几天、几周甚至几个月)自动缩放。

这是我当前的脚本:

import seaborn as sns
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates    
from matplotlib.dates import AutoDateFormatter, AutoDateLocator

plot_df.fillna(0,inplace=True)
fig, axHM = plt.subplots(1,1,figsize=(30,5))

axHM = sns.heatmap(plot_df.T, cmap='rocket')
locator = mdates.AutoDateLocator()
formatter = mdates.AutoDateFormatter(locator)

axHM.xaxis.set_major_locator(locator)
axHM.xaxis.set_major_formatter(formatter)
fig.autofmt_xdate()

我得到了这个图,x 轴以很好的格式显示日期,但比例完全错误,从 1970 年开始,而不是我的日期时间日期来自表格:

在此处输入图像描述

任何帮助表示赞赏! 谢谢

虽然我不知道为什么 AutoDateFormatter 不起作用,但我找到了另一种方法来做我想做的事情:

x_labels = plot_df.index[::10].tolist()
plt.xticks(range(0,len(plot_df.index),10), x_labels)
fig.autofmt_xdate()

并删除以下内容:

locator = mdates.AutoDateLocator()
formatter = mdates.AutoDateFormatter(locator)
axHM.xaxis.set_major_locator(locator)
axHM.xaxis.set_major_formatter(formatter)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM