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

Plotly中为散点图插入的图片添加边框的正确方法

在Plotly散点图中为插入图片添加精准对齐边框

要给Plotly散点图里的插入图片加边框,关键是让矩形形状的坐标和图片的位置、尺寸完全匹配。因为你的图片使用了xanchor="center"和yanchor="middle"(锚点在图片中心),所以可以通过图片的sizex/sizey来计算矩形的边界坐标。

核心思路

图片中心坐标为(x,y),横向尺寸sizex=2,因此矩形左右边界为x ± sizex/2;纵向尺寸sizey=2,上下边界为y ± sizey/2。同时要保证矩形的xref和yref与图片一致,都绑定到坐标轴。

完整代码示例

import plotly.express as px
from PIL import Image

xs = [0, 1, 2]
ys = [0, 1, 4]
image_paths = ["a.png", "b.png", "c.png"]

figure = px.scatter(x=xs, y=ys)

size = 2

for x, y, img_path in zip(xs, ys, image_paths):
    # 添加图片
    figure.add_layout_image(
        x=x,
        y=y,
        source=Image.open(img_path),
        xref="x",
        yref="y",
        sizex=size,
        sizey=size,
        xanchor="center",
        yanchor="middle",
    )
    # 添加对应边框
    figure.add_shape(
        type="rect",
        x0=x - size/2,
        x1=x + size/2,
        y0=y - size/2,
        y1=y + size/2,
        xref="x",
        yref="y",
        line=dict(color="red", width=2),
        fillcolor="rgba(0,0,0,0)",  # 透明填充避免遮挡图片
        layer="below"  # 边框置于图片下层,防止覆盖内容
    )

figure.show()

参数说明

  • x0/x1:矩形左右边界,基于图片中心x坐标加减半幅宽度(size/2)
  • y0/y1:矩形上下边界,基于图片中心y坐标加减半幅高度(size/2)
  • layer="below":确保边框在图片下方,不遮挡图片内容
  • fillcolor="rgba(0,0,0,0)":完全透明填充,仅显示边框线条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:22:33