Plotly Python中为散点图添加箭头的实现问题
解决Plotly添加散点指向指定坐标箭头的问题
问题描述
我参考了相关内容尝试在Plotly图形中添加箭头,但代码中标记段落无法正常运行,需求是添加从散点图中的点指向x_end、y_end对应坐标点的箭头,效果示意图如下:

尝试的代码:
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") layout = go.Layout( yaxis=dict(scaleanchor="x", scaleratio=1), template = "plotly_white", title="<b>V</b>", ) fig.layout = layout fig.update_layout( xaxis = dict(autorange="reversed") ) ################## arrow = go.layout.Annotation(dict( x= x_end, y= y_end, xref="x", yref="y", text="", showarrow=True, axref = "x", ayref='y', ax= x_start, ay= y_start, arrowhead = 3, arrowwidth=1.5, arrowcolor='rgb(255,51,0)',) ) x_end = [1, 2, 4] y_end = [6, 5, 6] fig.update_layout( annotations= dict(x_end, y_end,)) ################### fig.write_html("Fig.html") fig.show()
问题原因
- 未定义
x_start和y_start,这两个值需要从散点图的数据源(DataFrame的a、b列)获取 - 单个
Annotation对象无法处理多组箭头坐标,需为每个箭头创建独立的Annotation实例 - 更新
annotations时传入格式错误,应传入Annotation对象列表而非字典
修正后的代码
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") layout = go.Layout( yaxis=dict(scaleanchor="x", scaleratio=1), template = "plotly_white", title="<b>V</b>", ) fig.layout = layout fig.update_layout( xaxis = dict(autorange="reversed") ) # 箭头终点坐标 x_end = [1, 2, 4] y_end = [6, 5, 6] # 散点起始坐标(从DataFrame中提取) x_start = df['a'].tolist() y_start = df['b'].tolist() # 批量创建箭头注释 annotations = [] for xs, ys, xe, ye in zip(x_start, y_start, x_end, y_end): arrow = go.layout.Annotation( x=xe, y=ye, xref="x", yref="y", text="", showarrow=True, axref="x", ayref="y", ax=xs, ay=ys, arrowhead=3, arrowwidth=1.5, arrowcolor='rgb(255,51,0)' ) annotations.append(arrow) # 将所有箭头添加到图形中 fig.update_layout(annotations=annotations) fig.write_html("Fig.html") fig.show()
说明
- 通过
zip遍历散点起始坐标和箭头终点坐标,为每一组坐标创建独立的箭头注释对象 - 确保起始坐标与散点图的数据源一一对应,保证箭头从散点出发
- 将所有箭头对象存入列表后批量添加到布局,实现多箭头的正确绘制
内容的提问来源于stack exchange,提问作者Elena Greg
相关产品推荐
相关产品推荐

