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

Plotly柱状图传递文本时注释显示NaN问题求助

问题描述

需要创建包含两个子图的可视化:

  1. 展示乌克兰各行业银行放贷规模
  2. 展示各行业最大放贷机构的市场份额

数据中包含top_lender_name_market_share列(字符串类型,内容为机构名称+市场份额),但将该列作为第二个柱状图的条形注释传入时,注释显示为NaN。已尝试以下操作:

  • 传入单个字符串/数字可正常显示
  • 传入纯字母列、非数值列、转列表后的目标列均失败

疑问:Plotly的GO柱状图注释是否仅接受数值型?为何text = str(1)可正常工作?

附相关代码:

# set subplot parameters
fig = make_subplots(rows = 1, cols = 2, column_widths=[2, 1],
                    subplot_titles=('Performing loans volume',"     Market share"),
                    shared_yaxes=True, horizontal_spacing = 0.02)

# add data structures
fig.add_trace(go.Bar(x = df['perf_balance_sum'], y = df['Industry_eng'], orientation = 'h',
                     text =  df['perf_balance_sum'], name = 'Market perf loans', marker = dict(color='steelblue'),
                    textfont=dict(size=11, family='Amalia', color='black')))

# WHY DOES THIS NOT WORK!!!!!! i want to show the value from df['top_lender_name_market_share'] within the bar showing the df['top_lender_market_share']
fig.add_trace(go.Bar(x = df['top_lender_market_share'], y = df['Industry_eng'], orientation = 'h',
                     text = df['top_lender_name_market_share'], name  = 'top ms',), col = 2, row = 1)

# add layout structures
#general layout and titles
fig.update_layout(title = 'Lending by industry as of {}',
                  title_font_size = 16, title_font_family="Amalia", title_font_color="blue",
                  font_family="Amalia", font_color="black", font_size=11,
                  legend=dict(yanchor="top", y=0.5, xanchor="left", x=0.2, bgcolor=None),
                  legend_title_font_color="black",
                  height = 600, width = 1100,
                  barmode = 'overlay', yaxis=dict(type = 'category', categoryorder = 'trace'))

# add/format labels
fig.update_xaxes(row = 1, col = 1, title_text = 'Performing loans in UAH bn', title_font=dict(size=13, family='Amalia', color='black'), tickfont=dict(family='Amalia', color='darkblue', size=11), range=[0,160])
fig.update_xaxes(row = 1, col = 2, title_text = 'Top ms %', title_font=dict(size=13, family='Amalia', color='black'), tickfont=dict(family='Amalia', color='darkblue', size=11), range=[0,50])

fig.update_yaxes(row = 1, col = 1, title_text = "Industry", title_font=dict(size=13, family='Amalia', color='black'), tickfont=dict(family='Amalia', color='darkblue', size=11))
fig.update_yaxes(row = 1, col = 2, title_text = None, tickfont=dict(family='Amalia', color='darkblue', size=11))

# format annotation in bars
fig.update_traces(texttemplate='%{text:1.1f}', textposition='outside')
fig.update_traces(texttemplate='%{text:1.1f}', col = 2, textposition='inside')
fig.update_annotations(font_size=14)

#deactivate legend for the two right subplots
for trace in fig['data']:
    if trace['name'] in ['raif ms', 'top ms']:
        trace['showlegend'] = False

fig.show()

问题根源

核心问题出在**texttemplate的格式化规则不匹配**:

  • 给第二个子图设置了texttemplate='%{text:1.1f}',这个语法强制将text内容按浮点数格式化,但df['top_lender_name_market_share']是包含机构名称的字符串,Plotly无法将其解析为浮点数,因此输出NaN。
  • text = str(1)能正常工作,是因为此时未指定texttemplate,Plotly默认直接显示字符串内容;如果给str(1)加上%{text:1.1f}模板,同样会显示NaN。

Plotly的text参数并不只接受数值型,只要texttemplate规则与text内容类型匹配即可。

解决思路与修改方案

  1. 针对不同子图的text类型,设置对应的texttemplate:
    • 第一个子图的text是数值型,保留%{text:1.1f}格式化规则
    • 第二个子图的text是字符串型,使用%{text}直接输出原始内容

修改代码中格式化注释的部分:

# 给第一个子图的数值型注释设置格式化
fig.update_traces(texttemplate='%{text:1.1f}', textposition='outside', col=1)
# 给第二个子图的字符串型注释设置无格式输出
fig.update_traces(texttemplate='%{text}', textposition='inside', col=2)
fig.update_annotations(font_size=14)
  1. 额外验证:
    • 确认df['top_lender_name_market_share']列没有空值,可通过df['top_lender_name_market_share'].isna().sum()检查,若有空值需先填充或过滤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:02:43