You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Plotly Express子图实现目标样式的饼图与分组柱状图

问题与解决方案

问题描述

尝试使用Plotly创建包含饼图和分组柱状图的子图,但当前生成结果不符合预期,需要调整代码使饼图呈现带外侧标签、中心总计文字的样式,分组柱状图呈现按性别分组的样式。

修改方案

饼图样式调整

  1. 配置标签显示格式与位置,将标签和百分比展示在饼图外侧
  2. 为饼块添加白色边框增强视觉区分度
  3. 添加饼图中心的总计文字注释
  4. 移除冗余图例

分组柱状图样式调整

  1. 修正分组逻辑:为每个性别单独创建柱状图轨迹
  2. 设置柱状图为分组模式
  3. 为不同性别指定匹配样式的颜色
  4. 补充坐标轴标题完善图表信息

修改后完整代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:10:27