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

如何在Plotly中将标注对齐至整个图表的边缘?

解决方法

要将标注固定在整个图表的右下角,不受绘图区域边距变化的影响,你需要把标注的参考系从paper改为container:

  • 使用xref="container"和yref="container":参考整个图表容器(包含标题、边距、坐标轴等所有元素),而非仅绘图区域
  • 设置x=1、y=0:对应容器的右下角坐标
  • 配合xanchor="right"、yanchor="bottom":让标注的右下角对齐容器的右下角,避免标注超出边界

修改后的代码如下:

import plotly.express as px

fig = px.scatter(x=[1, 2, 3], y=[1, 2, 3], title="Try panning or zooming!")

fig.add_annotation(
    text="Container-positioned annotation (bottom-right)",
    xref="container", yref="container",
    x=1, y=0,
    xanchor="right", yanchor="bottom",
    showarrow=False,
    margin={"r": 10, "b": 10}  # 可选:添加小边距避免紧贴边缘
)

fig.show()

关键参数说明

  • container参考系:坐标范围是[0,1],(0,0)对应容器左上角,(1,1)对应容器右上角
  • xanchor和yanchor:控制标注文本相对于x/y坐标的对齐方式,设置为right和bottom后,标注的右下角会精准对齐容器的右下角
  • 可选的margin:可以微调标注和容器边缘的距离,让显示更美观

内容的提问来源于stack exchange,提问作者Václav Bočan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:02:06