我想知道如何才能将栏内的文本更改为表示百分比而不是数字.我查看了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()

enter image description here

推荐答案

我会转换数据,然后将文本和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()

plot

更新:如何分别修改每个条形图的文本

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

percentage = (df / df.sum()).applymap(lambda x: f'{x:.0%}')

创建要打印的地物:

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

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

使用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
)

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

plot

Full code to get the same plot
(comment barmode='group' to get relative representation)

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()

Python相关问答推荐

使用索引列表列表对列进行切片并获取行方向的向量长度

在Python Attrs包中,如何在field_Transformer函数中添加字段?

如何列举Pandigital Prime Set

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

Telethon加入私有频道

如何从.cgi网站刮一张表到rame?

Django RawSQL注释字段

基于形状而非距离的两个numpy数组相似性

如何杀死一个进程,我的Python可执行文件以sudo启动?

Pandas:计算中间时间条目的总时间增量

Flask运行时无法在Python中打印到控制台

如何过滤组s最大和最小行使用`transform`'

使用嵌套对象字段的Qdrant过滤

操作布尔值的Series时出现索引问题

如何将验证器应用于PYDANC2中的EACHY_ITEM?

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?

大Pandas 中的群体交叉融合

Pandas 数据框自定义排序功能

如何有效地计算所有输出相对于参数的梯度?

如何导入与我试图从该目录之外运行的文件位于同一目录中的Python文件?