Trim and Format Date Axis Formatting for Dataframe in HeatMap

14 views Asked by At
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns


df = pd.DataFrame(np.random.rand(113, 3), columns = ["116", "118", "120"])

dates = pd.date_range(start = pd.to_datetime("today"), periods = 113, freq = "D")
df.index = dates

fig, ax = plt.subplots()

ax = sns.heatmap(df, annot=True, fmt="g", cmap='coolwarm', cbar_kws={"shrink": 0.9}, 
        annot_kws={'size': 'x-small', 'alpha': 0.8}                           
        )

From this code, I would like to format the date shown on the heapmap. I would like to display just the date without time and ideally show a date every 3-4 tick marks. The default output looks like "2023-11-26T12:42:43.934334343433".

I have been through the post below and several others and haven't been able to find something that works. I could reformat the dates at one point but the tick marks were not matching up or correct.

Pandas bar plot changes date format

With a smaller set of data, like 10 data points the following works:

ax.set_yticklabels([x.strftime("%Y-%m-%d") for x in df.index])

But with 113 datapoints, I get this:

ValueError: The number of FixedLocator locations (29), usually from a call to set_ticks, does not match the number of labels (113).

There are too many datapoints so a limited number of ticks are being shown, but now sure how to tell how many ticks there are or just format what's there.

0

There are 0 answers