在海上热图上显示日期 [英] Show dates on seaborn heatmap

查看:80
本文介绍了在海上热图上显示日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用seaborn库从pandas数据帧创建热图.这是代码:

I am trying to create a heat map from pandas dataframe using seaborn library. Here, is the code:

test_df = pd.DataFrame(np.random.randn(367, 5), 
                 index = pd.DatetimeIndex(start='01-01-2000', end='01-01-2001', freq='1D'))

ax = sns.heatmap(test_df.T)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%d'))

但是,我得到的图形没有在x轴上打印任何内容.

However, I am getting a figure with nothing printed on the x-axis.

推荐答案

Seaborn heatmap是分类图.它从0缩放到number of columns - 1,在这种情况下从0缩放到366. datetime定位器和格式化程序期望将值作为日期(或更准确地说,是与日期相对应的数字).对于有问题的年份,其数字应介于730120(= 01-01-2000)和730486(= 01-01-2001)之间.

Seaborn heatmap is a categorical plot. It scales from 0 to number of columns - 1, in this case from 0 to 366. The datetime locators and formatters expect values as dates (or more precisely, numbers that correspond to dates). For the year in question that would be numbers between 730120 (= 01-01-2000) and 730486 (= 01-01-2001).

因此,为了能够使用matplotlib.dates格式化程序和定位器,您需要首先将数据帧索引转换为datetime对象.然后,您将无法使用热图,而只能使用允许数字轴显示的图表,例如imshow图.然后,您可以将即时显示图的范围设置为与要显示的日期范围相对应.

So in order to be able to use matplotlib.dates formatters and locators, you would need to convert your dataframe index to datetime objects first. You can then not use a heatmap, but a plot that allows for numerical axes, e.g. an imshow plot. You may then set the extent of that imshow plot to correspond to the date range you want to show.

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

df = pd.DataFrame(np.random.randn(367, 5), 
                 index = pd.DatetimeIndex(start='01-01-2000', end='01-01-2001', freq='1D'))

dates = df.index.to_pydatetime()
dnum = mdates.date2num(dates)
start = dnum[0] - (dnum[1]-dnum[0])/2.
stop = dnum[-1] + (dnum[1]-dnum[0])/2.
extent = [start, stop, -0.5, len(df.columns)-0.5]

fig, ax = plt.subplots()
im = ax.imshow(df.T.values, extent=extent, aspect="auto")

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))

fig.colorbar(im)
plt.show()

这篇关于在海上热图上显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆