Search code examples
pythonmatplotlibseaborn

Date formatting in seaborn heatmap axis


I'm trying to apply the date formatting in the x-axis of the seaborn heatmap; but it doesn't apply properly. The code is given below

# Import library
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

# initialize list of lists
data = [
        ['15-12-2023', 'Australia', 78], 
        ['15-12-2023', 'Europe', 98],
        ['15-12-2023', 'Mexico', 65],
        ['15-12-2023', 'Peru', 87],
        ['17-12-2023', 'Australia', 73],
        ['17-12-2023', 'Europe', 95],
        ['17-12-2023', 'Mexico', 84],
        ['17-12-2023', 'Peru', 68],
        ['16-12-2023', 'Australia', 90],
        ['16-12-2023', 'Europe', 91],
        ['16-12-2023', 'Mexico', 94],
        ['16-12-2023', 'Peru', 93],
    ]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['createdtime', 'Region', 'SuccessRate'])
df['createdtime'] = pd.to_datetime(df['createdtime'], format='%d-%m-%Y', errors='raise')
df = df.sort_values('createdtime', ascending=False)
df = df.pivot_table(index="Region", columns="createdtime", values="SuccessRate", fill_value=0)

# plot the heatmap
fig, (ax) = plt.subplots(1, 1, figsize=(3, 3))
sns.set()
sns.heatmap(df, 
            cmap="YlOrRd_r", 
            annot=True, 
            linewidths=.1, 
            fmt='.2f', 
            square=True, 
            cbar=False, 
            annot_kws={
                'fontsize' : 9 })

# format the x-axis
date_form = DateFormatter("%d-%m")
ax.xaxis.set_major_formatter(date_form)

It shows the wrongly formatted x-axis data

enter image description here

Any help is highly appreciated. Thanks!


Solution

  • DateFormatter doesn't work well with pandas. One option might be to modify the columns after pivoting using strftime:

    df = df.pivot_table(index="Region", columns="createdtime", values="SuccessRate", fill_value=0)
    df.columns = df.columns.strftime('%d-%m')
    

    and remove

    date_form = DateFormatter("%d-%m")
    ax.xaxis.set_major_formatter(date_form)
    

    Output:

    enter image description here