[Python] Plot and annotate NaN values in a seaborn heatmap

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Seaborn heatmap based on a DataFrame containing some NaN values. The heatmap turns out to just have those cells blank. However, I would like a custom color, e.g., light grey to be drawn with an 'NaN' annotation. How can I achieve this?

    import seaborn as sns
    import matplotlib.pyplot as plt
    from matplotlib.colors import LogNorm, Normalize
    import numpy as np
    import pandas as pd

    data = {
    "Server (%)": [np.nan, 0.2, 2.4],
    "Scheduler (%)": [np.nan, 2.3, 4.5]
    }
    merged_summary = pd.DataFrame(data)

    # Prepare annotation matrix
    annot = merged_summary.copy()
    for i in range(annot.shape[0]):
    for j in range(annot.shape[1]):
    val = annot.iat[i, j]
    if pd.isna(val):
    annot.iat[i, j] = "N/A"
    elif val > 1:
    annot.iat[i, j] = f"{val:.1f} %"
    else:
    annot.iat[i, j] = f"{val:.3f} %"

    fig, ax = plt.subplots(3,1, figsize=(5,7), constrained_layout=True)
    h2 = sns.heatmap(
    data=merged_summary,
    annot=annot.values,
    fmt='',
    cmap="coolwarm",
    cbar=False,
    linewidths=0.5,
    linecolor='white',
    mask=merged_summary.isna(),
    vmin=0.1,
    vmax=30,
    norm=LogNorm(vmin=0.1, vmax=30),
    annot_kws={"size": 8},
    ax=ax[2],
    )
    plt.show()


    [​IMG]

    Continue reading...

Compartilhe esta Página