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

如何在Matplotlib饼图图例中显示受访者总人数?

在Matplotlib饼图图例中显示总人数的实现方法

有两种实用方式可以实现需求,具体代码及说明如下:

方法一:在图例中添加单独的总人数条目

这种方式会在图例里新增一行,专门标注总人数:

import matplotlib.pyplot as plt

# 定义数据
yes = 90
no = 255
total = yes + no  # 自动计算总人数,数据更新时无需手动修改
labels = ['Yes', 'No']

# 生成带具体人数的图例标签,再添加上总人数条目
legend_labels = [f'{label} ({count}人)' for label, count in zip(labels, [yes, no])]
legend_labels.append(f'总人数: {total}人')

sizes = [yes, no]
fig, ax = plt.subplots()
# 绘制饼图,此处可去掉原代码的labels参数,避免图表上重复显示标签
ax.pie(sizes, autopct='%1.1f%%')
# 调整图例位置,避免遮挡饼图
ax.legend(legend_labels, loc='upper right', bbox_to_anchor=(1.3, 0.9))

plt.title('是否使用过该产品')
plt.show()

方法二:将总人数设为图例标题

这种方式更简洁,把总人数放在图例的顶部标题位置:

import matplotlib.pyplot as plt

yes = 90
no = 255
total = yes + no
labels = ['Yes', 'No']

# 生成带具体人数的图例标签
legend_labels = [f'{label} ({count}人)' for label, count in zip(labels, [yes, no])]

sizes = [yes, no]
fig, ax = plt.subplots()
# 保留原代码的labels参数,让饼图上显示基础标签
ax.pie(sizes, labels=labels, autopct='%1.1f%%')
# 设置图例标题为总人数,同时展示带人数的详细标签
ax.legend(legend_labels, title=f'总人数: {total}人', loc='upper right', bbox_to_anchor=(1.3, 0.9))

plt.title('是否使用过该产品')
plt.show()

补充说明

  • 两种方法都能清晰展示各选项的具体人数和总人数
  • bbox_to_anchor参数用于调整图例位置,你可以根据实际布局修改数值
  • 用total = yes + no自动计算总人数,能让代码在数据更新时自动适配,更具灵活性

内容的提问来源于stack exchange,提问作者Lagrange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:52:57