如何在Plotly Express绘制的柱状图中保留2位小数?
解决Plotly Express柱状图百分比保留两位小数的问题
方案1:修正texttemplate格式并全局应用
你尝试的texttemplate = "%{y:.2f}%"格式逻辑正确,可能是因为未确保格式应用到所有trace或文本显示位置问题,修改代码如下:
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:.2f}%", textposition="inside" ) fig8.layout["legend"]["title"] = "Type of clients' membership" fig8.show()
方案2:手动计算百分比(更可控)
如果方案1仍不生效,建议提前在数据中计算百分比,绕过barnorm自动计算的不确定性:
# 提前计算每组的占比百分比 new_data['active_pct'] = (new_data['active'] / (new_data['active'] + new_data['inactive'])) * 100 new_data['inactive_pct'] = (new_data['inactive'] / (new_data['active'] + new_data['inactive'])) * 100 fig8 = px.bar( new_data, x=["Loyal", "Exited"], y=["active_pct", "inactive_pct"], title="Distribution of active membership in loyal and exited clients group", width=700, orientation="v", color_discrete_map={"active_pct": "green", "inactive_pct": "yellow"}, barmode="stack", texttemplate="%{y:.2f}%" # 直接在绘图时设置文本格式 ) fig8.update_layout( xaxis_title_text="Types of clients", yaxis_title_text="Number of clients, %" ) fig8.layout["legend"]["title"] = "Type of clients' membership" # 修正图例名称,去掉后缀 fig8.for_each_trace(lambda t: t.update(name=t.name.replace('_pct', ''))) fig8.show()
失效原因说明
使用barnorm="percent"时,Plotly动态计算百分比值,若trace的文本属性未正确绑定计算后的值,会导致格式化失效。方案1强制对所有trace应用格式;方案2通过提前计算让数值完全可控,避免内部计算的不确定性。
内容的提问来源于stack exchange,提问作者Victoria Yermolenko
相关产品推荐
相关产品推荐

