堆叠柱状图底部Trace文本无法显示在外部的解决方法
解决Plotly堆叠柱状图底部Trace文本外部显示问题
因为Plotly堆叠柱状图中,当某Trace上方有其他Trace堆叠时,textposition='outside'会自动将文本移至内部避免遮挡,所以要实现底部Trace的百分比外部显示,需要用**自定义注释(annotations)**替代Trace自带的文本功能,具体修改如下:
修改后的代码
import plotly.graph_objects as go bar2 = go.Figure() # 添加底部的Halted Trials Trace,移除原text相关设置 bar2.add_trace(go.Bar( name='Halted Trials', x=bar2_df['Condition'], y=bar2_df['Halted'], marker=dict(color='rgb(252, 141, 98)') )) # 添加Total Trials Trace bar2.add_trace(go.Bar( name='Total Trials', x=bar2_df['Condition'], y=bar2_df['Total'], marker=dict(color='rgb(252, 200, 179)') )) # 循环添加自定义注释,将百分比显示在底部柱子外部(下方) total_max = bar2_df['Total'].max() for idx, row in bar2_df.iterrows(): bar2.add_annotation( x=row['Condition'], y=-total_max * 0.05, # 基于总数据最大值设置偏移,确保文本在柱子下方 text=f"{row['Percent']:.2f}%", showarrow=False, font=dict(size=10, color='black') ) bar2.update_layout( barmode='stack', yaxis_title='Clinical Trials', width=1000, height=1000, margin=dict(l=0, r=0, t=0, b=50, pad=0), # 增加底部边距,避免文本被截断 legend=dict( orientation='h', yanchor='bottom', y=-.3, xanchor='center', x=.5 ), plot_bgcolor='white', yaxis=dict( # 调整Y轴范围,留出下方显示注释的空间,同时上方预留少量空白 range=[-total_max * 0.1, bar2_df['Halted'].max() + bar2_df['Total'].max() * 1.1] ) )
关键修改说明
- 移除Trace自带文本:删除底部Trace的
text、texttemplate、textposition参数,避免Plotly自动将文本移至内部。 - 自定义注释定位:通过
add_annotation循环为每个类别添加百分比文本,设置y为负数偏移量,将文本固定在柱子下方的外部区域。 - 调整图表范围与边距:修改Y轴范围确保注释可见,同时增加底部边距防止文本被图表边界截断。
内容的提问来源于stack exchange,提问作者Becca
相关产品推荐
相关产品推荐

