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

如何在Python Plotly图表的图形间添加箭头?

在Plotly矩形间添加自定义向右箭头的实现方法

核心是利用Plotly的add_annotation()方法配置箭头,以下是具体步骤和代码示例:

1. 基础矩形图表搭建(可替换为你已有的代码)

先创建三个间隔排列的矩形作为基础:

import plotly.graph_objects as go

fig = go.Figure()

# 添加三个矩形
fig.add_shape(
    type="rect",
    x0=0, y0=0.2, x1=1, y1=0.8,
    fillcolor="lightblue", line_color="blue"
)
fig.add_shape(
    type="rect",
    x0=2, y0=0.2, x1=3, y1=0.8,
    fillcolor="lightgreen", line_color="green"
)
fig.add_shape(
    type="rect",
    x0=4, y0=0.2, x1=5, y1=0.8,
    fillcolor="lightpink", line_color="pink"
)

2. 添加自定义向右箭头

通过add_annotation()配置箭头的起点、终点和样式,每个箭头对应一对相邻矩形:

# 第一个箭头:从第一个矩形右侧中间指向第二个矩形左侧中间
fig.add_annotation(
    x=2, y=0.5,          # 箭头终点坐标
    ax=1, ay=0.5,        # 箭头起点坐标
    xref="x", yref="y",
    axref="x", ayref="y",
    showarrow=True,
    arrowhead=2,         # 箭头头部样式(1-8可选,2为实心箭头)
    arrowwidth=2,        # 箭头线条宽度
    arrowcolor="black",  # 箭头颜色
    arrowsize=1          # 箭头头部缩放比例
)

# 第二个箭头:从第二个矩形右侧中间指向第三个矩形左侧中间
fig.add_annotation(
    x=4, y=0.5,
    ax=3, ay=0.5,
    xref="x", yref="y",
    axref="x", ayref="y",
    showarrow=True,
    arrowhead=2,
    arrowwidth=2,
    arrowcolor="black",
    arrowsize=1
)

3. 优化布局并展示

调整坐标轴范围,确保箭头和矩形完整显示:

fig.update_layout(xaxis_range=[-0.5, 5.5], yaxis_range=[0, 1])
fig.show()

4. 批量添加箭头(灵活扩展)

如果矩形数量较多,可通过循环批量生成箭头,避免重复代码:

# 存储所有矩形的x轴边界
rect_x_bounds = [{"x0":0, "x1":1}, {"x0":2, "x1":3}, {"x0":4, "x1":5}]

# 循环添加箭头
for i in range(len(rect_x_bounds)-1):
    fig.add_annotation(
        x=rect_x_bounds[i+1]["x0"], y=0.5,
        ax=rect_x_bounds[i]["x1"], ay=0.5,
        xref="x", yref="y",
        axref="x", ayref="y",
        showarrow=True,
        arrowhead=2,
        arrowwidth=2,
        arrowcolor="black"
    )

你可以根据需求修改箭头的arrowhead、arrowwidth、arrowcolor等参数,实现自定义样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:18:26