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

Plotly Dash:如何将图表内文本移至右上角或图表上方

调整"Avg. Mileage"文本位置的两种方案

方案一:将Indicator整体移到图表右上角

直接修改Indicator的domain参数,把它定位到右上角区域,标题会跟着Indicator一起移动:

@app.callback(Output('mileage_kpi','figure'),Input('input_place','value'))
def mileage_kpi(inpu):
    fig = go.Figure(go.Indicator(
        mode = "number",
        value = df4.mileage.mean(),
        title = {"text": "平均里程(Avg. Mileage)"},
        # 调整domain到右上角:x取0.7-1(右侧30%宽度),y取0.8-1(顶部20%高度),可按需微调
        domain = {'y': [0.8, 1], 'x': [0.7, 1]}))
    fig.add_trace(go.Scatter(y = df4.mileage))
    
    fig.update_layout(xaxis = {'range': [0, 68]})
    return fig

domain的x/y范围是0到1(对应图表宽高的比例),调整后Indicator和标题会固定在右上角区域。

方案二:用annotations单独放置标题(更灵活)

如果想把标题和Indicator分开(比如标题放上方左侧,Indicator留右上角),推荐用fig.add_annotation()自定义文本位置,完全不受Indicator限制:

示例1:标题放在图表上方左侧

@app.callback(Output('mileage_kpi','figure'),Input('input_place','value'))
def mileage_kpi(inpu):
    fig = go.Figure(go.Indicator(
        mode = "number",
        value = df4.mileage.mean(),
        # 去掉Indicator自带的title,改用自定义annotation
        domain = {'y': [0.8, 1], 'x': [0.7, 1]}))  # Indicator仍放右上角
    fig.add_trace(go.Scatter(y = df4.mileage))
    
    # 添加自定义标题到上方左侧
    fig.add_annotation(
        x=0,  # 对应图表最左侧
        y=1.1,  # 超出图表顶部的位置
        text="平均里程(Avg. Mileage)",
        showarrow=False,
        font=dict(size=14, weight='bold'),
        xref="paper",  # 基于图表比例定位,不受数据轴影响
        yref="paper"
    )
    
    fig.update_layout(
        xaxis = {'range': [0, 68]},
        margin=dict(t=50)  # 顶部留足空间,避免标题被截断
    )
    return fig

示例2:标题放在图表右上角(与Indicator分开)

@app.callback(Output('mileage_kpi','figure'),Input('input_place','value'))
def mileage_kpi(inpu):
    fig = go.Figure(go.Indicator(
        mode = "number",
        value = df4.mileage.mean(),
        domain = {'y': [0.7, 0.9], 'x': [0.7, 0.9]}))  # Indicator放右上角偏下位置
    fig.add_trace(go.Scatter(y = df4.mileage))
    
    # 添加标题到右上角
    fig.add_annotation(
        x=1,  # 对应图表最右侧
        y=1.1,  # 超出图表顶部的位置
        text="平均里程(Avg. Mileage)",
        showarrow=False,
        font=dict(size=14, weight='bold'),
        xref="paper",
        yref="paper",
        xanchor="right"  # 文本右对齐,防止超出图表边界
    )
    
    fig.update_layout(
        xaxis = {'range': [0, 68]},
        margin=dict(t=50, r=20)
    )
    return fig

xref="paper"和yref="paper"表示基于图表整体比例定位,不会随数据变化;margin参数用来调整图表四周空白,避免标题被截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:05:34