简体   繁体   English

seaborn 热图轴中的日期

[英]Date in seaborn heatmap axis

I'm plotting a heatmap that relates number of cases, age range and date.我正在绘制一个与病例数、年龄范围和日期相关的热图。 However I couldn't reduce the x-axis label to %d-%b (eg, 15-Dec).但是我无法将 x 轴 label 减少到 %d-%b (例如,15-Dec)。 How can I change this?我怎样才能改变这个? My data is in Pastebin .我的数据在Pastebin中。 在此处输入图像描述

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

%matplotlib inline

df_general = pd.read_csv('df_general.csv')
df_general['Date'] = pd.to_datetime(df_general['Date'])

fig = plt.figure(figsize = (15,5))

y_axis_labels = ['0 to 1', '1 to 9', '10 to 19', '20 to 29', '30 to 39',
                '40 to 49', '50 to 59', '60 to 69', '70 to 79', '80 to 89',
                '> 90']

covid_matrix = df_general.pivot('FAIXA_ETARIA', 'Date', 'count')

sns.heatmap(covid_matrix, xticklabels = 30, yticklabels = y_axis_labels, cmap='coolwarm')
#x-axis ticklabels between 30 dates

When I define a list with specific labels, adding m e replacing xticklabels value, the graph gets worse:当我定义一个带有特定标签的列表,添加我替换 xticklabels时,图表变得更糟:

m = ('01-Jan', '01-Fev', '01-Mar', '01-Apr', '01-May', '01-Jun', '01-Jul', '01-Ago', '01-Sep', '01-Oct', '01-Nov', '01-Dec')

sns.heatmap(covid_matrix, xticklabels = m, yticklabels = y_axis_labels, cmap='coolwarm')
#x-axis ticklabels with m value

在此处输入图像描述

You can't simply format the x-axis as dates as heatmap will only show those dates that are in your covid_matrix ;您不能简单地将 x 轴格式化为日期,因为热图只会显示您heatmap中的covid_matrix there will be no gaps in the heatmap for missing dates (as for instance for dates between 2020-13-01 and 2020-02-02).缺少日期(例如 2020 年 13 月 1 日和 2020 年 2 月 2 日之间的日期)的热图中不会有空白。

The easiest way is to just take the values for the selected tick locations (every 30th column in your example) from the formatter dictionary used for the x axis and reformat them as desired:最简单的方法是从用于 x 轴的格式化程序字典中获取所选刻度位置的值(在您的示例中每 30 列),然后根据需要重新格式化它们:

ax = sns.heatmap(covid_matrix, xticklabels = 30, yticklabels = y_axis_labels, cmap='coolwarm')
ax.xaxis.set_ticklabels([pd.to_datetime(value).strftime('%d-%b') for value in ax.xaxis.get_major_formatter().func.args[0].values()])

or alternatively take the column header values for the selected columns (floor to int as labels in heatmap are at positions between column values):或者选择列 header 值作为选定列(从地板到 int,因为热图中的标签位于列值之间的位置):

ax.xaxis.set_ticklabels([d.strftime('%d-%b') for d in covid_matrix.columns[ax.get_xticks().astype(int)]])

在此处输入图像描述

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

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