如何通过Plotly Express子图实现目标样式的饼图与分组柱状图
问题与解决方案
问题描述
尝试使用Plotly创建包含饼图和分组柱状图的子图,但当前生成结果不符合预期,需要调整代码使饼图呈现带外侧标签、中心总计文字的样式,分组柱状图呈现按性别分组的样式。
修改方案
饼图样式调整
- 配置标签显示格式与位置,将标签和百分比展示在饼图外侧
- 为饼块添加白色边框增强视觉区分度
- 添加饼图中心的总计文字注释
- 移除冗余图例
分组柱状图样式调整
- 修正分组逻辑:为每个性别单独创建柱状图轨迹
- 设置柱状图为分组模式
- 为不同性别指定匹配样式的颜色
- 补充坐标轴标题完善图表信息
修改后完整代码
import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # 替换为你的真实数据 df_pie = pd.DataFrame({'index': ['A', 'B', 'C', 'D'], 'count': [25, 30, 20, 25]}) df_bar = pd.DataFrame({ 'Satisfaction': ['Very Satisfied', 'Satisfied', 'Neutral', 'Dissatisfied', 'Very Dissatisfied']*2, 'Gender': ['Male']*5 + ['Female']*5, 'count': [15, 20, 10, 5, 3, 12, 18, 12, 7, 4] }) # 创建子图,移除饼图不需要的共享y轴设置 specs = [[{'type':'pie'}, {"type": "bar"}]] fig = make_subplots(rows=1, cols=2, specs=specs, subplot_titles=['Pie Chart', 'Grouped Bar Chart']) # 调整饼图样式 fig.add_trace(go.Pie( labels=df_pie['index'], values=df_pie['count'], hole=0.6, marker_colors=['#353837','#646665', '#8e9492', '#c9d1ce'], textinfo='label+percent', textposition='outside', marker=dict(line=dict(color='#ffffff', width=2)), showlegend=False ), 1, 1) # 添加饼图中心总计文字 fig.add_annotation( text=f'Total<br>{df_pie["count"].sum()}', x=0.12, y=0.5, font_size=16, showarrow=False, row=1, col=1 ) # 构建分组柱状图 for gender in df_bar['Gender'].unique(): filtered_df = df_bar[df_bar['Gender'] == gender] fig.add_trace(go.Bar( x=filtered_df['Satisfaction'], y=filtered_df['count'], name=gender, marker_color='#353837' if gender == 'Male' else '#8e9492' ), 1, 2) # 整体布局优化 fig.update_layout( title=dict( text="Visualization", font=dict(family="Arial", size=20, color='#283747'), x=0.5 ), barmode='group', yaxis_title='Count', xaxis2_title='Satisfaction' ) fig.show()
内容的提问来源于stack exchange,提问作者WF30
相关产品推荐
相关产品推荐

