Plotly 3D折线图自定义按钮点击后注释不显示问题
Plotly 3D折线图按钮切换后注释仅显示单个的问题修复
问题描述
点击自定义按钮后,Plotly 3D折线图的注释未正常显示:预期点击「Member Ids」按钮后显示所有线路的构件注释,但当前仅在左下角显示「Member 35」,其余注释全部缺失。
相关说明
xxx是长度为tmm的二维数组,存储线路的3D坐标点mem_index存储每个构件的ID
问题代码
anno=[] for i in range(0,tmm,2): fig2.add_trace(go.Scatter3d(x=xxx[i:i+2,2],y=xxx[i:i+2,0],z=xxx[i:i+2,1], mode='lines', line=dict( color="black", width=10),)) ax= xxx[i,2].item() bx= xxx[i+1,2].item() ay= xxx[i,0].item() by= xxx[i+1,0].item() az= xxx[i,1].item() bz= xxx[i+1,1].item() x_annotate=((ax+bx)/2)+0.1 y_annotate=((ay+by)/2)+0.1 z_annotate=((az+bz)/2)+0.1 #(x_annotate, y_annotate, z_annotate) a1= dict( showarrow=False, x=x_annotate, y=y_annotate, z=z_annotate, text=f"Member {mem_index[kk]}", font=dict( color="black", size=8 ),) anno.append(a1) kk= kk+1 button1= [True for i in range ( fig2)] Model.update_layout( updatemenus=[ dict( type = "buttons", direction = "left", buttons=list([ dict( args=[{'visible': button1}, {"title": "RC Model", "annotations": []}], label="RC Model", method="update", ), dict( args=[{'visible': button1}, {"title": "Members ID's", "annotations": anno}], label="Member Ids", method="update" ), pad={"r": 10, "t": 10}, showactive=True, x=0.11, xanchor="left", y=1.1, yanchor="middle" ), ] ) Model.update_layout(height=800, width=800) Model.show()
问题截图

修复方案
核心问题分析
- 3D注释坐标系未指定:代码中生成的注释未设置
xref/yref/zref属性,Plotly默认使用画布百分比坐标系,导致所有注释堆积在画布左下角(坐标原点附近),仅能看到最上层的一个。 button1数组生成错误:直接遍历fig2(Figure对象)会生成长度异常的数组,可能导致trace可见性控制失效。- 变量
kk未初始化:未在循环前定义kk=0,会触发索引错误。
修正后的代码
anno=[] kk = 0 # 初始化构件ID索引 for i in range(0,tmm,2): fig2.add_trace(go.Scatter3d(x=xxx[i:i+2,2],y=xxx[i:i+2,0],z=xxx[i:i+2,1], mode='lines', line=dict( color="black", width=10),)) ax= xxx[i,2].item() bx= xxx[i+1,2].item() ay= xxx[i,0].item() by= xxx[i+1,0].item() az= xxx[i,1].item() bz= xxx[i+1,1].item() x_annotate=((ax+bx)/2)+0.1 y_annotate=((ay+by)/2)+0.1 z_annotate=((az+bz)/2)+0.1 a1= dict( showarrow=False, x=x_annotate, y=y_annotate, z=z_annotate, xref="x", # 指定注释参考3D x轴 yref="y", # 指定注释参考3D y轴 zref="z", # 指定注释参考3D z轴 text=f"Member {mem_index[kk]}", font=dict( color="black", size=8 ), ) anno.append(a1) kk= kk+1 # 生成与trace数量匹配的可见性数组 button1= [True] * len(fig2.data) Model.update_layout( updatemenus=[ dict( type = "buttons", direction = "left", buttons=list([ dict( args=[{'visible': button1}, {"title": "RC Model", "annotations": []}], label="RC Model", method="update", ), dict( args=[{'visible': button1}, {"title": "Members ID's", "annotations": anno}], label="Member Ids", method="update" ), ]), pad={"r": 10, "t": 10}, showactive=True, x=0.11, xanchor="left", y=1.1, yanchor="middle" ), ] ) Model.update_layout(height=800, width=800) Model.show()
修复说明
- 坐标系指定:添加
xref="x"、yref="y"、zref="z"后,注释会基于3D折线图的坐标轴定位,准确显示在对应线路的中间偏移位置。 - 可见性数组修正:
len(fig2.data)获取图中所有trace的数量,生成对应长度的True数组,确保按钮切换时所有线路正常显示。 - 索引初始化:添加
kk=0避免循环时出现未定义变量的错误,保证每个注释对应正确的构件ID。
内容的提问来源于stack exchange,提问作者Tabish Izhar
相关产品推荐
相关产品推荐

