Search code examples
pythonmatplotlibseaborn

Skip nan annotation in seaborn heatmap


How is it possible to drop the nans in the heatmap annotation while keeping the colorcoding?

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

data =  np.random.random((15,15))
df = pd.DataFrame(data)
annot_df = df.applymap(lambda f: f'{f:.1f}')
annot_df=annot_df.to_numpy()
np.put(annot_df,np.random.choice(annot_df.size, 21, replace=False),np.nan)
fig = plt.figure(figsize=(10,10))
sns.heatmap(
    df,
    cbar=False,
    annot=annot_df,
    fmt="",
    annot_kws={"size": 10, "va": "center_baseline"},
    cmap="magma",
    vmin=-1,
    vmax=1,
    square=True)
plt.show()

Heatmap

Masking only also removes the colorcoding.


Solution

  • The mask argument for sns.heatmap is for situations where you want to mask data by value and not apply heatmap coloring on the masked cells. If you want to just drop the annotation altogether but keep the coloring, you can use empty string in place of np.nan in your annotations.

    import seaborn as sns
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = np.random.random((15, 15))
    df = pd.DataFrame(data)
    annot_df = df.applymap(lambda f: f"{f:.1f}")
    annot_df = annot_df.to_numpy()
    np.put(annot_df, np.random.choice(annot_df.size, 21, replace=False), "") # The only change here
    fig = plt.figure(figsize=(10, 10))
    sns.heatmap(
        df,
        cbar=False,
        annot=annot_df,
        fmt="",
        annot_kws={"size": 10, "va": "center_baseline"},
        cmap="magma",
        vmin=-1,
        vmax=1,
        square=True,
    )
    plt.show()
    

    heatmap with nans replaced with empty strings