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

Plotly柱状图顶部显示值的小数位数如何设置为动态变量

问题

我在制作柱顶显示数值的Plotly柱状图时,添加柱序列的代码如下:

fig.add_bar(
    # x=df.index,
    x=df['Wellname'],
    y=df.iloc[:,-1].values, 
    marker={"color": 'gray'},  
    name='Pad '+pad, 
    row=row,
    col=1,
    legendgroup = '1',
    text=df.iloc[:,-1].values,
)

固定保留2位小数时,用下面的代码可以正常实现效果:

fig.update_traces(texttemplate='%{text:.2f}', textposition='outside',row=1,col=1)

现在需要把保留小数位数改为动态变量,尝试了如下写法但无法生效:

num_digit=function(key)
fig.update_traces(texttemplate='%{text:.%{num_digit}f}', textposition='outside',row=1,col=1)

柱顶标签效果示意图

解答

失效原因是Plotly的texttemplate语法不支持嵌套占位符,内层的%{num_digit}不会被解析为外部Python变量,你需要在Python层先拼接好完整的模板字符串,再传入参数,有两种常用实现方式:

方法1:f-string拼接模板(推荐,代码最简洁)

用Python f-string提前把动态小数位数嵌入模板字符串,注意f-string里原本的%{需要写成%{{做转义,避免被f-string识别为Python表达式:

num_digit = function(key) # 先获取到需要保留的小数位整数值
fig.update_traces(
    texttemplate=f'%{{text:.{num_digit}f}}',
    textposition='outside',
    row=1,
    col=1
)

方法2:提前格式化文本内容

如果后续有更复杂的自定义格式需求,也可以在传入text参数时就把数值格式化为目标字符串,texttemplate直接读取文本内容即可:

num_digit = function(key)
# 提前把所有y值格式化为对应小数位的字符串
formatted_col = [f"{val:.{num_digit}f}" for val in df.iloc[:,-1].values]
fig.add_bar(
    x=df['Wellname'],
    y=df.iloc[:,-1].values, 
    marker={"color": 'gray'},  
    name='Pad '+pad, 
    row=row,
    col=1,
    legendgroup = '1',
    text=formatted_col,
)
# 直接读取预格式化的文本,不需要再做数值格式化
fig.update_traces(
    texttemplate='%{text}',
    textposition='outside',
    row=1,
    col=1
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 22:39:26