如何在 Plotly Express 中减少 bar 中的小数位数?

问题描述 投票:0回答:1

我需要您的帮助,将 Ployly Express 创建的条形图中的小数位数减少到 2 位。 enter image description here 我的代码是:

    fig8 = px.bar( new_data, x=["Loyal", "Exited"], y=["active", "inactive"], title="Distribution of active membership in loyal and exited clients group", width=700,         orientation="v", color_discrete_map={"active": "green", "inactive": "yellow"}, barmode="stack" ) fig8.update_layout(xaxis_title_text="Types of clients", yaxis_title_text="Number of clients, %", barnorm="percent") fig8.update_traces(marker_line_width = 0, texttemplate = "%{y}%") fig8.layout["legend"]["title"] = "Type of clients' membership" fig8.show()

对于我的条形图,我使用了这个表格,其中数据不是百分比。我选择了 barnorm="percent",但无法将其更改为小数点后两位。enter image description here

我使用了很多建议,例如 text_auto="%.2f" 和 texttemplate = "%{y:%.2f}%"。没有帮助。

python plotly bar-chart decimalformat texttemplate
1个回答
0
投票

您可以使用以下命令将小数位数限制为小数点后 2 位:

fig8.update_traces(
    marker_line_width = 0, 
    texttemplate = "%{value:.2f}%"
) 

这是完整的代码和结果条形图:

import pandas as pd
import plotly.express as px

new_data = pd.DataFrame({
    "IsActiveMember": ['Exited','Loyal'],
    "active": [735, 4416],
    "inactive": [1302, 3547],
})
new_data = new_data.set_index("IsActiveMember")

fig8 = px.bar( 
    new_data, 
    x=["Loyal", "Exited"], 
    y=["active", "inactive"], 
    title="Distribution of active membership in loyal and exited clients group", 
    width=700,         
    orientation="v", 
    color_discrete_map={"active": "green", "inactive": "yellow"}, 
    barmode="stack" 
) 
fig8.update_layout(
    xaxis_title_text="Types of clients", 
    yaxis_title_text="Number of clients, %", 
    barnorm="percent"
) 

fig8.update_traces(
    marker_line_width = 0, 
    texttemplate = "%{value:.2f}%"
) 

fig8.layout["legend"]["title"] = "Type of clients' membership" 

fig8.show()

© www.soinside.com 2019 - 2024. All rights reserved.