I need to reduce the decimal places to 2 in my bar chart created by Plotly Express.
My code is:
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()
For my bar chart, I've used this table where the data is not in percentages. I've chosen the barnorm="percent"
and I can't change it to 2 decimal places.
I have tried different suggestions, such as setting text_auto="%.2f"
and texttemplate = "%{y:%.2f}%"
. It didn't help.
You can use the following to limit the number of decimals to 2 places after the decimal point:
fig8.update_traces(
marker_line_width = 0,
texttemplate = "%{value:.2f}%"
)
Here is the full code and resulting bar chart:
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()