[Python] seaborn heatmap cell style for nan-Values

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

  1. Stack

    Stack Membro Participativo

    I have created a heatmap with seaborn in a jupyter notebook:

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

    sns.set(rc={"figure.figsize": (10, 10), })
    sns.set(font_scale=0.9)
    ax = plt.subplots()
    ax = sns.heatmap(
    forHeatmap,
    square=True, # make cells square
    cbar_kws={'fraction' : 0.01, 'label': 'Länge (km)'}, # shrink colour bar
    cmap='OrRd', # use orange/red colour map
    linewidth=0.5 # space between cells
    )


    And the output (without label on the axis) looks like this: [​IMG]

    Unfortunately I cannot show the underlying data, but it is a pandas dataframe with the index set on the variable s How can I cange the style (not just the color!) for the Nan-values? I would like to have them as grey squares, just as the squares representing values.

    EDIT: When I do the same with small testdata, it looks like this:

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

    data = pd.DataFrame(
    {"x": (1, 2, 3, 4), "y": (1, 2, np.nan, 4), "z": (14, 15, 23, 2)}
    ).set_index("x")



    The dataframe looks now like it, with the index set on the first column (x):

    [​IMG]

    Now, I plot with this:

    sns.set(
    rc={
    "figure.figsize": (5, 5),
    }
    )
    sns.set(font_scale=0.9)
    ax = plt.subplots()
    ax = sns.heatmap(
    data,
    square=True, # make cells square
    cmap="OrRd", # use orange/red colour map
    linewidth=0.5, # space between cells
    )



    And the result is:

    [​IMG]

    As shown, the cell for the nan-value is represented as 4 small squares instead of one. How can I change it? As I couldn't find a thread regarding this topic I think it may be jupyter notebook related?

    Continue reading...

Compartilhe esta Página