Change heatmap's yticks for multi-index dataframe

Viewed 170

Below is the seaborn heatmap generated from a MultiIndex dataframe:

import numpy as np
import pandas as pd
import seaborn as sns

years = range(2016,2019)
months = range(1,6)
df = pd.DataFrame(index=pd.MultiIndex.from_product([years,months]))
df['vals'] = np.random.random(size=len(df))
sns.heatmap(df)

The above heatmap's yticks show both years and months. Is there a way to change the heatmap's yticks to only show the years, like below?

1 Answers

Use the yticklabels param of sns.heatmap to set custom labels

  1. Create a list of empty strings except at the desired indexes

    Either: Only show labels when the month is 3

    labels = [year if month == 3 else '' for year, month in df.index]
    

    Or: Only show labels on specific rows (index 2, 7, and 12 in OP's example)

    labels = [year if row in (2, 7, 12) else ''
              for row, (year, month) in enumerate(df.index)]
    
  2. Then set these labels via yticklabels

    sns.heatmap(df, yticklabels=labels)
    

Notes:

  • These conditions like month == 3 and row in (2, 7, 12) are specific to OP's example and will need to be adjusted for real data.
  • If you have a datetime index (not just strings), see this answer for spacing out datetime yticks.

Related