Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

python - 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 (e.g., 15-Dec). How can I change this? My data is in Pastebin. enter image description here

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:

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't simply format the x-axis as dates as heatmap will only show those dates that are in your 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).

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:

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):

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...