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

使用Plotly绘制仪表盘图如何上移标题并在各颜色区间添加文本

解决方法

你需要对代码做两处修改即可实现需求:

  • 调整标题位置:在Indicator的title参数中新增y属性,数值越高标题位置越靠上,推荐设置为0.85~0.9区间,可根据实际显示效果自行调整
  • 新增区间文本标注:调用add_annotation方法分别在三个颜色区间对应位置添加文本,关闭箭头显示即可

修改后的完整代码如下:

import plotly.graph_objects as go

fig = go.Figure(go.Indicator(
    mode = "gauge",
    domain = {'x': [0, 1], 'y': [0, 1]},
    # 新增y参数上移标题
    title = {'text': "water level", 'font': {'size': 16}, 'y': 0.9},
    gauge = {
        'axis': {'range': [None, 370], 'tickwidth': 2, 'tickcolor': "black", 'tickvals':[90,260,370],},
        'bar': {'color': "lightgrey"},
        'bgcolor': "white",
        'borderwidth': 1.5,
        'bordercolor': "white",
        'steps': [
            {'range': [0, 90], 'color': "green"},
            {'range': [90, 260], 'color': 'yellow'},
            {'range': [260, 370], 'color': "red"}, ],}))

# 添加绿色区间safe标注
fig.add_annotation(
    x=0.17, y=0.28,
    text="safe",
    showarrow=False,
    font=dict(size=14)
)
# 添加黄色区间average标注
fig.add_annotation(
    x=0.5, y=0.08,
    text="average",
    showarrow=False,
    font=dict(size=14)
)
# 添加红色区间dangerous标注
fig.add_annotation(
    x=0.83, y=0.28,
    text="dangerous",
    showarrow=False,
    font=dict(size=14)
)

fig.update_layout(paper_bgcolor = "white", font = {'color': "black", 'family': "Arial"})
fig.show()

如果标注位置不符合你的显示需求,可以微调每个annotation的x、y数值,x控制左右偏移,y控制上下偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:27:02