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

Plotly中title_side设置异常:图例标题居中失效且图例损坏

Python Plotly PCA绘图:图例标题居中问题修复

我是Python绘图新手,正在针对不同人群进行PCA分析。用Plotly做可视化时遇到难题:尝试设置图例标题居中,添加title_side参数后不仅没实现居中效果,反而导致图例损坏,甚至散点图整体偏移。

原代码

fig = px.scatter(pca, x='PC1', y='PC2', color='#LOC', template="seaborn")

fig.update_layout(legend=dict(
    title="<i> metapopulation <i>",
    title_side="top",
    orientation="h",
    entrywidthmode='fraction',
    entrywidth=.2,
    x=.5),
    autosize=False,
    height=800,
    width=800
)

fig.update_xaxes(title_text = f"PC1 ( {pve.at[pve.index[0], 0]} %)",
                 range=(-0.05, 0.2),
                 constrain='domain')
fig.update_yaxes(title_text = f"PC2 ( {pve.at[pve.index[1], 0]} %)",
                 scaleanchor="x",
                 scaleratio=1)

fig.show()

效果对比

  • 异常图(图例损坏+图偏移):异常图例及散点图
  • 正常原图:正常PCA图

问题原因与修复方案

  • 图例标题居中的正确设置:仅设置legend.x=.5只能让图例区域居中,要让标题单独居中,需添加title_x=0.5参数。
  • 标签语法错误:原代码中斜体标签未正确闭合(<i>需对应</i>),可能导致渲染异常。
  • 图例布局冲突:水平图例默认在图上方易遮挡散点,建议调整y值将图例移至图下方,同时增加底部边距避免截断。

修复后的代码

fig = px.scatter(pca, x='PC1', y='PC2', color='#LOC', template="seaborn")

fig.update_layout(
    legend=dict(
        title="<i>metapopulation</i>",  # 修正斜体标签闭合
        title_side="top",
        title_x=0.5,  # 强制标题居中
        orientation="h",
        entrywidthmode='fraction',
        entrywidth=.2,
        x=0.5,  # 图例区域整体居中
        y=-0.15  # 将图例移至图下方,避免遮挡散点
    ),
    autosize=False,
    height=800,
    width=800,
    margin=dict(b=100)  # 增加底部边距,防止图例被截断
)

fig.update_xaxes(
    title_text=f"PC1 ( {pve.at[pve.index[0], 0]} %)",
    range=(-0.05, 0.2),
    constrain='domain'
)
fig.update_yaxes(
    title_text=f"PC2 ( {pve.at[pve.index[1], 0]} %)",
    scaleanchor="x",
    scaleratio=1
)

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:57:27