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

使用matplotlib_venn为韦恩图添加百分比遇0.0%显示问题求助

问题分析与解决

问题原因

你的代码里百分比显示为0.0%有两个核心问题:

  1. 百分比计算误用缩小后数值:你在count_formatter里先把原始客户数除以1000转成千单位,之后计算百分比时用的是这个缩小后的值,分子过小直接导致结果趋近于0。
  2. 整体客户群分母计算错误:sum(branch_counts.values)是各品牌记录数的总和,会重复统计跨多个品牌的客户,而整体客户群应该是去重后的总客户数,错误的分母进一步放大了计算偏差。

修正后的代码

import matplotlib.pyplot as plt
import matplotlib_venn as venn

def count_formatter(count, total_customers):
    # 用原始客户数计算百分比
    percentage = 100 * count / total_customers
    # 转千单位用于显示
    count_k = count / 1000
    return f'{count_k:.1f}K ({percentage:.1f}%)'

# 获取去重后的总客户数(作为百分比计算的正确基数)
total_customers = df['customerid'].nunique()

# 转换为各品牌的客户集合
branch_sets = [set(group_data['customerid']) for _, group_data in df.groupby('brand')]

plt.figure(figsize=(10, 10))

# 生成韦恩图,传入正确的总客户数用于计算百分比
venn.venn3(
    subsets=branch_sets, 
    set_labels=['A', 'B', 'C'], 
    subset_label_formatter=lambda count, total=total_customers: count_formatter(count, total)
)

plt.show()

关键修改点

  • 新增total_customers:通过df['customerid'].nunique()获取去重后的总客户数,作为百分比计算的正确分母。
  • 调整count_formatter逻辑:先使用原始客户数计算百分比,再将数值转成千单位用于显示,避免数值缩小导致的计算错误。
  • 修正subset_label_formatter传入参数:把之前错误的branch_counts替换为正确的total_customers。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:15:27