Plotly Dash更新3D图时部分文本注释字体变小问题求助
解决Plotly 3D文本注释动态更新时字体大小异常的问题
问题原因
Plotly Scatter3d 模式下的文本元素属于3D空间内的渲染对象,会受透视视角影响自动调整显示大小,即使显式设置固定字体大小,动态更新时仍可能出现部分文本缩放异常的情况。
解决方案
改用Plotly布局中的**3D注释(annotations)**替代Scatter3d的文本轨迹,注释是叠加在3D场景上的2D元素,字体大小完全可控,不会受透视视角或位置变化影响。
修改后的完整代码
import plotly.graph_objs as go import dash from dash import html, dcc, Input, Output import random import itertools def generate_figure(data): text_positions = [[[-1,-1,0], [-1,1,0]], [[1,-1,0], [1,1,0]]] fig = go.Figure() # 创建3D注释列表 annotations = [] for row, rows in enumerate(text_positions): for col, pos in enumerate(rows): text_content = f"{data['row'][row] if data['row'][row] is not None else 'N/A'} x {data['col'][col] if data['col'][col] is not None else 'N/A'}" annotations.append( dict( x=pos[0], y=pos[1], z=pos[2], text=text_content, showarrow=False, font=dict(size=12, color='black'), xanchor='center', yanchor='middle' ) ) fig.update_layout( scene=dict( xaxis=dict(range=[-2, 2]), yaxis=dict(range=[-2, 2]), zaxis=dict(range=[-1, 1]), annotations=annotations ) ) return fig app = dash.Dash(__name__) app.layout = html.Div([ dcc.Graph(id='graph'), html.Button('Refresh data', id='btn') ]) @app.callback( Output('graph', 'figure'), Input('btn', 'n_clicks') ) def update_graph(n_clicks): data = [0,1,2,3] col = list(random.choice(list(itertools.combinations(data, 2)))) row = [item for item in data if item not in col] return generate_figure({'col': col, 'row': row}) if __name__ == '__main__': app.run(debug=True)
关键修改说明
- 移除
Scatter3d文本轨迹,改用scene.annotations添加独立注释 - 每个注释单独设置坐标、文本内容和字体属性,确保字体大小固定为12
- 设置
showarrow=False隐藏注释箭头,保持界面简洁 - 通过
xanchor和yanchor确保文本在目标位置居中显示
内容的提问来源于stack exchange,提问作者Raphael_Ratz
相关产品推荐
相关产品推荐

