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

Plotly中添加两组不同颜色箭头:红色箭头被覆盖如何解决?

Plotly中同时显示两组不同颜色箭头的解决方法

问题原因

你看不到红色箭头是因为第二次调用fig.update_layout(annotations=list_of_all_arrows2)时,直接用绿色箭头的列表替换了之前添加的红色箭头列表,而非将两组箭头合并追加。

解决方法

把两组箭头的列表合并,再一次性更新到图表的annotations中即可:

  • 保留两组箭头的生成代码,删除两次单独的fig.update_layout(annotations=...)调用
  • 将两个箭头列表合并,用合并后的列表执行一次布局更新

修改后的完整代码

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

d = {'a': [1, 2, 2], 'b': [3, 5, 4], 'c': [0.1, 0.2, 0.6]}
df = pd.DataFrame(data=d)

fig = px.scatter(df, x='a', y='b', error_y='c')

fig.update_xaxes(title_font_family="Trebuchet")
fig.update_layout(yaxis=dict(scaleanchor="x", scaleratio=1),
                  template = "plotly_white",
                  title="<b>V</b>",
                 )
fig.update_layout(xaxis = dict(autorange="reversed"))

x_end = [1, 2, 2]
y_end = [3, 5, 4]
x_start = [0, 1, 3]
y_start = [4, 4, 4]

# 生成红色箭头列表
list_of_all_arrows = []
for x0,y0,x1,y1 in zip(x_end, y_end, x_start, y_start):
    arrow = go.layout.Annotation(dict(
                    x=x0,
                    y=y0,
                    xref="x", yref="y",
                    text="",
                    showarrow=True,
                    axref="x", ayref='y',
                    ax=x1,
                    ay=y1,
                    arrowhead=3,
                    arrowwidth=1.5,
                    arrowcolor='rgb(255,51,0)',)
                )
    list_of_all_arrows.append(arrow)

# 生成绿色箭头列表
list_of_all_arrows2 = []
for x0,y0,x1,y1 in zip([i-2 for i in x_end], [i-3 for i in y_end], x_start, y_start):
    arrow = go.layout.Annotation(dict(
                    x=x0,
                    y=y0,
                    xref="x", yref="y",
                    text="",
                    showarrow=True,
                    axref="x", ayref='y',
                    ax=x1,
                    ay=y1,
                    arrowhead=3,
                    arrowwidth=1.5,
                    arrowcolor='green',)
                )
    list_of_all_arrows2.append(arrow)

# 合并两组箭头并更新布局
fig.update_layout(annotations=list_of_all_arrows + list_of_all_arrows2)

# fig.write_html("Fig.html")
fig.show()

补充说明

如果后续需要继续添加更多箭头,可先获取当前已有箭头列表,再与新箭头列表合并:

existing_annotations = fig.layout.annotations
fig.update_layout(annotations=existing_annotations + new_arrows_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:10:44