更改 Plotly Express 条形图中的文本

dln*_*vss 2 python plotly plotly-express

我想知道如何更改条形内的文本以表示百分比而不是数字。我查看了plotly库,似乎我能做到这一点的唯一方法是使用plolty.graph_objects。有什么办法可以避免使用plotly.graph_objects?

编辑:我的目标是让 y 轴保留值,但图表中的文本显示百分比。本质上,我想自定义图表中的文本。

这是我试图放入图表中的数据,该数据将变成数据框(df):

    Use-Cases   2018    2019    2020    2021
0   Consumer    50      251     2123    210
1   Education   541     52      32      23
2   Government  689     444     441     456

df=pd.read_excel('Book1.xlsx')
df=df.transpose()
fig=px.bar(df,template='seaborn',text_auto='.3s')
fig.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Vit*_*are 5

我将转换数据,然后将文本和 Y 标签格式化为.0%. 另外,我会将 x 轴类型更改为分类,以避免表示中间值。

from io import StringIO
import pandas as pd
import plotly.express as px

data='''
    Use-Cases   2018    2019    2020    2021
0   Consumer    50      251     2123    210
1   Education   541     52      32      23
2   Government  689     444     441     456
'''

df = pd.read_csv(StringIO(data), sep='\s+').set_index('Use-Cases')

fig = px.bar(
    (df / df.sum()).T,
    template='seaborn',
    text_auto='.0%',
)

fig.update_layout(
    xaxis={
        'type': 'category',
        'showgrid': False,
    },
    yaxis={
        'tickformat': '.0%'
    }
)

fig.show()
Run Code Online (Sandbox Code Playgroud)

阴谋

更新:如何单独修改每个栏的文本

让我们使用与上面相同的数据框df并准备一个百分比表(我们将使用它来单独更新每个条形的文本):

percentage = (df / df.sum()).applymap(lambda x: f'{x:.0%}')
Run Code Online (Sandbox Code Playgroud)

创建要绘制的图形:

fig = px.bar(
    df.T,
    template='seaborn',
    barmode='group',
    title='Value and Percentage over years'
)

fig.update_xaxes(
    type='category',
    showgrid=False,
)
Run Code Online (Sandbox Code Playgroud)

使用for_each_trace迭代每个用例并对它们应用单独的text值:

fig.for_each_trace(
    lambda trace: trace.update(text=percentage.loc[trace.name])
)

fig.update_traces(
    textposition='outside'
    texttemplate='%{text}'   
    # use '%{y}<br>%{text}' to show values and percentage together
)
Run Code Online (Sandbox Code Playgroud)

这是我的输出,其中包含悬停数据和示例texttemplate='%{y}<br>%{text}'

阴谋

获得相同绘图的完整代码
(注释barmode='group'以获得相对表示)

from io import StringIO
import pandas as pd
import plotly.express as px

data='''
    Use-Cases   2018    2019    2020    2021
0   Consumer    50      251     2123    210
1   Education   541     52      32      23
2   Government  689     444     441     456
'''

df = pd.read_csv(StringIO(data), sep='\s+').set_index('Use-Cases').rename_axis(columns='year')

fig = px.bar(
    df.T,
    template='seaborn',
    barmode='group',
    title='Value and Percentage over years'
)

fig.update_xaxes(
    type='category',
    showgrid=False,
)

fig.update_yaxes(
    range=[0, 1.15*df.values.max()]
)

percentage = (df / df.sum()).applymap(lambda x: f'{x:.0%}')
fig.for_each_trace(lambda trace: trace.update(text=percentage.loc[trace.name]))

fig.update_traces(
    texttemplate='%{y}<br>%{text}',   # use '%{text}' to show only percentage
    textposition='outside'
)

fig.show()
Run Code Online (Sandbox Code Playgroud)