You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含热力图+散点图的Plotly图表自动缩放后出现额外内边距

解决Plotly热力图点击Autoscale后Y轴出现额外内边距的问题

你的代码生成带对角线的热力图后,点击工具栏的Autoscale会导致Y轴出现多余内边距,这是因为默认添加的scatter trace会影响Plotly的自动缩放计算,以下两种方法可以从根源解决:

方法一:将散点图设置为仅线条模式

默认情况下,go.Scatter会同时显示标记和线条,标记的边界会被计入自动缩放的范围,导致轴范围被扩大。只需将scatter的mode设为'lines',仅保留对角线线条:

import numpy as np
import plotly.graph_objects as go


def make_blob(n: int) -> np.ndarray:
    xx, yy = np.meshgrid(np.arange(n), np.arange(n))
    return np.exp(-((xx - n // 2) ** 2 + (yy - n // 2) ** 2) / (2 * (n // 2) ** 2))


if __name__ == "__main__":
    n = 101
    x = np.arange(n)
    blob = make_blob(n)
    fig = go.Figure(data=go.Heatmap(x=x, y=x, z=blob, type="heatmap", colorscale="Viridis"))
    # 修改scatter的mode为仅线条
    fig.add_scatter(x=x, y=x, mode='lines')
    fig.update_xaxes(range=(0, n - 1))
    fig.update_yaxes(range=(0, n - 1))
    fig.show()

方法二:排除散点图参与自动缩放计算

如果需要保留标记,可以设置轴的autoscaleexclude属性,让Autoscale仅考虑热力图的范围:

import numpy as np
import plotly.graph_objects as go


def make_blob(n: int) -> np.ndarray:
    xx, yy = np.meshgrid(np.arange(n), np.arange(n))
    return np.exp(-((xx - n // 2) ** 2 + (yy - n // 2) ** 2) / (2 * (n // 2) ** 2))


if __name__ == "__main__":
    n = 101
    x = np.arange(n)
    blob = make_blob(n)
    fig = go.Figure(data=go.Heatmap(x=x, y=x, z=blob, type="heatmap", colorscale="Viridis"))
    fig.add_scatter(x=x, y=x)
    # 设置排除scatter参与自动缩放
    fig.update_xaxes(range=(0, n - 1), autoscaleexclude=['scatter'])
    fig.update_yaxes(range=(0, n - 1), autoscaleexclude=['scatter'])
    fig.show()

原因说明

Plotly的Autoscale功能会计算所有可见trace的完整显示范围,包括散点标记的边缘区域。如果scatter使用默认的markers+lines模式,标记的尺寸会让轴范围被额外扩展,从而出现多余内边距。通过上述两种方法,要么去掉标记避免额外范围计算,要么直接排除scatter参与自动缩放,就能彻底解决这个问题。

内容的提问来源于stack exchange,提问作者Ziyuan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:16:18