Plotly Indicator仪表盘注释文本缩放时位置固定方法咨询
问题解决:仪表盘注释文本缩放偏移的固定对齐方案
问题说明
使用Dash+Plotly绘制Indicator仪表盘时,添加的中间注释文本在缩放图表时会发生位置偏移,无法与仪表盘保持固定对齐。
解决方案核心
问题根源在于默认注释的坐标系统基于整个图表容器(paper坐标系),而仪表盘使用的是自身的domain坐标系。将注释的坐标系统切换为与仪表盘一致的domain坐标系,即可实现注释与仪表盘的绑定对齐,缩放时同步位置。
具体修改点:
- 在
fig.add_annotation()中添加xref='domain'和yref='domain'参数,将注释的坐标参考系绑定到仪表盘的domain范围 - 可根据需求调整
x、y坐标值,确保文本处于仪表盘中间合适位置
修改后的完整代码
from dash import Dash, html, dcc, Input, Output import plotly.graph_objects as go from base64 import b64encode import io app = Dash(__name__) buffer = io.StringIO() val = 45 title = 'Max' fig = go.Figure() fig.add_trace( go.Indicator( domain={'x': [0, 1], 'y': [0, 1]}, title={ 'text': title, 'font_size': 40 }, value=val, number={ 'font_size': 50 }, mode='gauge + number', gauge={ 'shape': 'angular', 'steps': [ {'range': [0, 30], 'color': 'green'}, {'range': [30, 60], 'color': 'yellow'}, {'range': [60, 80], 'color': 'red'} ], 'bar': { 'color': 'black', 'thickness': 0.5 }, 'threshold': { 'line': {'color': 'orange', 'width': 8}, 'thickness': 0.8, 'value': 60 }, 'axis': {'range': [0, 80], 'tickformat': 's'} } ) ) fig.add_annotation( x=0.5, y=0.4, xref='domain', # 绑定仪表盘的domain坐标系 yref='domain', text='More than enough', font=dict( size=30, color='darkred' ), showarrow=True ) fig.write_html(buffer) html_bytes = buffer.getvalue().encode() encoded = b64encode(html_bytes).decode() app.layout = html.Div( [html.H2('Dashboard option'), dcc.Graph(id='Graph', figure=fig), html.A(html.Button('Download'), id='download', href='data:text/html;base64,' + encoded, download='plotly_graph.html')] ) if __name__ == '__main__': app.run_server(debug=True)
额外优化建议
- 如果不需要箭头,可将
showarrow设置为False,让界面更简洁 - 若需要微调文本位置,直接修改
x、y的数值(范围0-1,对应仪表盘的相对位置)即可
内容的提问来源于stack exchange,提问作者Sushil Kokil
相关产品推荐
相关产品推荐

