请求修改Python Plotly Dash水平条形图样式并添加概率渐变
需求说明
现有一个通过Python Plotly Dash实现的水平条形图,需要将其可视化样式修改为目标样式,同时根据概率值添加颜色渐变效果。
当前实现代码
def viz_proba_cause(df): """ Visualisation de probabilité de cause """ df = df.sort_values(by='proba_cause',ascending=True) fig = go.Figure() fig.add_trace(go.Bar( x=df['proba_cause'], y=df['failure_cause'], marker=dict( color='rgba(50, 171, 96, 0.6)', line=dict( color='rgba(50, 171, 96, 1.0)', width=1), ), name='Cause Probability', orientation='h', )) fig.update_layout( title='Cause Probability with symptome', ) annotations = [] # Adding labels for proba,state in zip(df['proba_cause'],df['failure_cause']): # labeling the bar net worth annotations.append(dict( y=state, x=proba+0.02, text=str(round(proba*100,2)) + '%', font=dict(family='Arial', size=12, color='rgb(50, 171, 96)'), showarrow=False)) fig.update_layout(annotations=annotations) return fig
修改后的代码
import plotly.graph_objects as go def viz_proba_cause(df): """ 故障原因概率可视化 """ # 保持原排序逻辑:按概率升序排列 df = df.sort_values(by='proba_cause', ascending=True) fig = go.Figure() fig.add_trace(go.Bar( x=df['proba_cause'], y=df['failure_cause'], # 绑定概率值实现颜色渐变 marker=dict( color=df['proba_cause'], colorscale='RdYlGn_r', # 红-黄-绿反向渐变,概率越高颜色越深绿 colorbar=dict( title='概率', tickformat='.0%' ), line=dict( color='rgba(255,255,255,0.8)', width=0.5 ) ), name='故障原因概率', orientation='h', width=0.8 # 调整条形间距,让布局更紧凑 )) # 对齐目标样式的布局调整 fig.update_layout( title={ 'text': '故障原因概率分布', 'x': 0.5, # 标题居中 'font': dict(size=16, family='Arial') }, # 隐藏网格线,简化坐标轴 xaxis=dict( showgrid=False, tickformat='.0%', title='' ), yaxis=dict( showgrid=False, title='' ), # 设置背景透明 plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', # 调整边距适配内容 margin=dict(l=100, r=20, t=60, b=40), showlegend=False # 隐藏图例,简化视觉 ) # 更新标注样式,确保在渐变背景下清晰可见 annotations = [] for proba, state in zip(df['proba_cause'], df['failure_cause']): annotations.append(dict( y=state, x=proba + 0.015, text=f'{round(proba*100,2)}%', font=dict(family='Arial', size=12, color='#333'), showarrow=False )) fig.update_layout(annotations=annotations) return fig
关键修改说明
- 颜色渐变:通过
marker.color绑定proba_cause字段,使用RdYlGn_r配色实现概率从低到高的红绿渐变,同时添加颜色条明确对应关系 - 样式适配:隐藏网格线、设置背景透明、调整标题居中样式、优化条形间距,让整体视觉更简洁
- 标注优化:将标注文字改为深灰色,确保在不同渐变颜色上都清晰可读,同时微调标注位置避免遮挡
- 布局细节:调整边距适配内容宽度,隐藏冗余图例,简化坐标轴标题
内容的提问来源于stack exchange,提问作者stat_man
相关产品推荐
相关产品推荐

