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

如何调整Plotly图例框尺寸?解决图例与图表重叠问题

解决Plotly横向图例与主图表重叠的问题

针对图例和图表重叠的问题,可以通过以下调整减小图例高度:

  • 给图例设置maxheight属性,强制限制图例最大高度,超出部分自动出现滚动条,避免占用过多垂直空间。
  • 缩小图例字体尺寸,同时减小图例项的图标宽度(itemwidth),进一步压缩垂直空间。
  • 减小图例项之间的间距(tracegroupgap),让布局更紧凑。

修改后的代码如下:

import plotly.graph_objects as go

fig = go.Figure()

for i in range(100):
    fig.add_trace(go.Scatter(
        x=[1,2],
        y=[1,2],
        name = f'{i}'*20,
        showlegend=True
    ))

fig.update_layout(
    autosize=True,
    minreducedheight=450,
    legend=dict(
        orientation="h",
        yanchor="bottom",
        y=1.02,
        xanchor="left",
        x=0,
        font=dict(size=8),  # 缩小字体
        itemwidth=20,       # 减小图例图标宽度
        maxheight=100,      # 设置图例最大高度,超出部分滚动
        tracegroupgap=0,    # 取消图例项之间的间距
        itemsizing='constant'  # 统一图例图标尺寸
    ),
)

fig.show()

这些调整会让横向图例的高度被限制在设定范围内,即使有大量图例项,也只会通过滚动条展示,不会和主图表区域重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:20:32