You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Plotly热力图网格线与单元格边界对齐的实现问询

Plotly热力图网格线与单元格边界对齐的实现问询

我使用plotlygraph_objects来生成heatmap,整体功能运行正常,但我想调整网格线的位置,让网格线与包含数值的单元格边界对齐;而当前的网格线是指向单元格中心的。

最小可复现示例

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()

当前效果

当前热力图效果:网格线处于单元格中心位置

需求

我希望将所有网格线整体偏移0.5个单元格的距离,使其与单元格边界对齐,但行和列的标签仍保持在单元格中心位置。请问这个需求可以实现吗?

备注:内容来源于stack exchange,提问作者Cleb

火山引擎 最新活动