环形堆叠饼图:如何设置依赖外层饼图的内层标签
解决堆叠饼图内层分组占比标签问题
我绘制了一个带百分比标签的堆叠饼图,外层饼图的标签符合预期,但内层饼图的标签需依赖其所属的外层饼图分组。例如,每个外层饼图颜色对应的内层饼图标签总和应为100%。目前红色外层饼图对应的内层标签为11.0%、12.0%、7.0%(基于整体的占比),希望改为对应红色分组内的占比(如35%、38%、27%),绿色和黄色分组同理。
要实现内层饼图显示组内占比,需要先计算每个外层分组下内层类别的相对比例,而非直接使用整体计数。以下是修改后的可复现代码:
import pandas as pd import numpy as np import random import matplotlib.pyplot as plt options = ['RED','YELLOW','GREEN'] color_list1 = [] color_list2 = [] for i in np.arange(100): color1 = random.choice(options) color2 = random.choice(options) color_list1.append(color1) color_list2.append(color2) test_df = pd.DataFrame(list(zip(color_list1, color_list2)), columns =['Outer_Color', 'Inner_Color']) # 计算外层分组的总数量 outer = test_df.groupby('Outer_Color').size() # 计算内层分组计数,并关联对应外层组的总数 inner = test_df.groupby(['Outer_Color', 'Inner_Color']).size().reset_index(name='count') inner['outer_total'] = inner['Outer_Color'].map(outer) # 计算组内占比(转换为百分比) inner['group_pct'] = (inner['count'] / inner['outer_total']) * 100 my_pal = {"RED": "r", "YELLOW": "yellow", "GREEN":"g"} fig, ax = plt.subplots(figsize=(14,7)) size = 0.3 # 绘制外层饼图(显示整体占比) ax.pie(outer.values.flatten(), radius=1, autopct='%1.1f%%', pctdistance=0.85, wedgeprops=dict(width=size, edgecolor='w'), colors=[my_pal[key] for key in outer.index]) # 自定义autopct函数,读取预先计算的组内占比生成标签 def custom_autopct(pct): current_pct = inner['group_pct'].iloc[custom_autopct.index] custom_autopct.index += 1 return f'{current_pct:.1f}%' custom_autopct.index = 0 # 绘制内层饼图(显示组内占比) ax.pie(inner['count'].values.flatten(), radius=1-size, autopct=custom_autopct, pctdistance=0.7, wedgeprops=dict(width=size, edgecolor='w'), colors=[my_pal[key] for key in inner['Inner_Color']]) plt.show()
关键修改说明
- 计算组内占比:新增
outer_total列关联外层组总数,通过count/outer_total得到每个内层类别在对应外层组内的占比 - 自定义标签生成:替换matplotlib默认的
autopct逻辑,使用预先计算好的组内百分比生成标签,确保每个外层组下的内层占比总和为100%
内容的提问来源于stack exchange,提问作者user9532692
相关产品推荐
相关产品推荐

