[Python] Align grid and cells in heatmap

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I use plotly's graph_objects to generate a heatmap. It all works well, however, I would like to shift the grid in such a way that its lines are aligned with the boundaries of the cells that contain the numbers; right now the grid lines point towards the center of the the cells.

    A minimal example:

    import numpy as np
    import plotly.graph_objects as go

    z = [[.1, .3, .5, .7, .9],
    [1, np.nan, .6, .4, .2],
    [.2, 0, np.nan, .7, .9],
    [.9, np.nan, np.nan, .2, 0],
    [.3, .4, np.nan, .7, 1]]

    cols = list("ABCDE")
    rows = list("12345")

    def plot_data(data: np.ndarray, cols: list[str], rows: list[str], title: str, color_scale: str = 'RdBu_r', colorbar_title: str = "") -> go.Figure:

    heatmap_fig = go.Figure()

    heatmap_fig.add_trace(
    go.Heatmap(
    z=data,
    x=cols,
    y=rows,
    colorscale=color_scale,
    text=[[f"{val:.2f}" if not np.isnan(val) else "" for val in row] for row in data],
    texttemplate="%{text}",
    textfont={"size": 10},
    showscale=True,
    colorbar=dict(
    title=colorbar_title,
    titleside="right",
    thickness=20,
    len=0.8
    ),
    xgap=2,
    ygap=2
    )
    )

    heatmap_fig.update_layout(
    title={
    'text': title,
    'y':0.95,
    'x':0.5,
    'xanchor': 'center',
    'yanchor': 'top'
    },
    height=400,
    width=None,
    yaxis_autorange='reversed',
    margin=dict(t=60, r=80, b=60, l=60),
    xaxis=dict(
    side='top',
    tickmode='linear',
    dtick=1,
    tickangle=0,
    showgrid=True,
    gridcolor='lightgrey',
    gridwidth=1,
    griddash='solid'
    ),
    yaxis=dict(
    showgrid=True,
    gridcolor='lightgrey',
    gridwidth=1,
    griddash='solid'
    ),
    plot_bgcolor='white'
    )

    return heatmap_fig

    fig = plot_data(z, cols, rows, "Test")
    fig.show()


    which produces

    [​IMG]

    So, all lines should be shifted by 0.5 cells but the row and column labels should remain centered. Is that possible?

    Continue reading...

Compartilhe esta Página