如何在 Python (Plotly Express) 中创建带有百分比值的条形图?

How do I create a bar chart with percentage values in Python (Plotly Express)?

我有一个显示我需要的一切的数据框,但最初我的 'No Show (%)' 速率计算显示在小数位:

                          Groups and Classes  Booked  Arrived  No Show (n)  No Show (%)
6            Supervised Exercise Program     121       57           64        5e-01
0                      Active Living 101       4        2            2        5e-01
2      Eating Well the Mediterranean Way      38       24           14        4e-01
5                                   MBCT     101       66           35        3e-01
4                  Healthy Meal Planning      33       22           11        3e-01
3                                  Grief      56       46           10        2e-01
1                         Craving Change     115       95           20        2e-01
Total                                NaN     468      312          156        3e-01

然后我得到以下图表:

mergedgcfig = mergedgc.sort_values('No Show (%)', ascending=True)
fig2 = px.bar(mergedgcfig, x='No Show (%)', y='Groups and Classes', text='No Show (%)', title='<b>Groups and classes no show rate</b>', template='simple_white', width=600, height=400)
fig2.update_traces(marker_color='#3EB595')
fig2.update_layout(uniformtext_minsize=8, uniformtext_mode='hide', autosize=False, title_x=0.7, title_font_family ="Calibri")
fig2.write_image('fig2.png')

这很好,但我想改为以百分比显示我的数据标签。

mergedgc['No Show (%)'] = mergedgc['No Show (%)'].transform(lambda x: '{:,.0%}'.format(x))

                      Groups and Classes  Booked  Arrived  No Show (n) No Show (%)
6            Supervised Exercise Program     121       57           64         53%
0                      Active Living 101       4        2            2         50%
2      Eating Well the Mediterranean Way      38       24           14         37%
5                                   MBCT     101       66           35         35%
4                  Healthy Meal Planning      33       22           11         33%
3                                  Grief      56       46           10         18%
1                         Craving Change     115       95           20         17%
Total                                NaN     468      312          156         33%

因此数据框最终显示了我想要的内容,但问题是当我尝试将其放入条形图中时,它会将百分比读取为分类变量。

我做错了什么?我基本上只希望我的未显示计算以百分比表示,并在条形图数据标签中显示这些百分比。看起来只要添加 % 符号,它就会转换为字符串。我以为会内置识别百分比,所以我不确定自己做错了什么。谁能帮我显示第一个数字,但带有百分比数据标签?

您只需将 text 字段更改为 text=[f'{i}%' for i in mergedgcfig['No Show (%)']]

mergedgcfig = mergedgc.sort_values('No Show (%)', ascending=True)
fig2 = px.bar(mergedgcfig, x='No Show (%)', y='Groups and Classes',  title='<b>Groups and classes no show rate</b>',
              template='simple_white', width=600, height=400, text=[f'{i}%' for i in mergedgcfig['No Show (%)']])
fig2.update_traces(marker_color='#3EB595')
fig2.update_layout(uniformtext_minsize=8, uniformtext_mode='hide', autosize=False, title_x=0.7, title_font_family ="Calibri")