如何在seaborn的countplot上添加百分比并修复hue场景下计算错误问题
解决方案
问题根源是patches的取值索引逻辑和分组求和规则不匹配:seaborn带hue的countplot中,patches的排序规则为先遍历完所有x轴分类的第一个hue值,再遍历所有x轴分类的第二个hue值,以此类推,之前的索引公式把x分类和hue的对应顺序搞反了,才会导致百分比计算异常。
以下是修改后可直接运行的代码:
import seaborn as sns import matplotlib.pyplot as plt import numpy as np df = sns.load_dataset("titanic") def with_hue(plot, num_x_categories, num_hue_categories): heights = [p.get_height() for p in plot.patches] patches = [p for p in plot.patches] # 按x轴分类分组计算每个分组的总数量,实现单x分类下百分比总和为100% for x_idx in range(num_x_categories): # 取当前x分类下所有hue对应的柱子高度求和作为分母 total = sum(heights[x_idx + hue_idx * num_x_categories] for hue_idx in range(num_hue_categories)) for hue_idx in range(num_hue_categories): # 计算当前柱子的正确索引 patch_idx = x_idx + hue_idx * num_x_categories percentage = '{:.1f}%'.format(100 * heights[patch_idx] / total) # 调整x坐标的偏移量适配居中 x = patches[patch_idx].get_x() + patches[patch_idx].get_width() / 2 - 0.15 y = patches[patch_idx].get_y() + patches[patch_idx].get_height() plot.annotate(percentage, (x, y), size = 11) plt.show() plt.figure(figsize=(12,8)) p3 = sns.countplot(x="class", hue="who", data=df) p3.set(xlabel='Class', ylabel='Count') with_hue(p3, 3, 3)
核心修改点
- 修正了patches的索引计算公式:同一x分类下不同hue的索引为
x_idx + hue_idx * 总x分类数,和seaborn的patches排序规则匹配 - 直接从当前x分类的所有hue柱子高度计算总和作为百分比分母,不需要额外调用数据集的value_counts,避免数据集排序和x轴排序不一致导致的计算错误
- 把函数内部硬编码的
p3替换为传入的plot参数,提高函数通用性
运行修改后的代码后,每个Class分类下的man、woman、child三个群体的百分比加总为100%,符合预期效果。
内容的提问来源于stack exchange,提问作者jexplore
相关产品推荐
相关产品推荐

