如何在饼图(pie plot)中隐藏指定分类的autopct百分比显示值
解决方案
pandas的饼图autopct参数除了格式化字符串外,还支持自定义规则实现部分扇区占比隐藏,这里提供两种常用实现方式:
方法1:自定义autopct回调函数
通过自定义百分比格式化函数,匹配到需要隐藏的扇区时返回空字符串即可:
# 先导入依赖,构造示例数据 import pandas as pd df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], 'radius': [2439.7, 6051.8, 6378.1]}, index=['Mercury', 'Venus', 'Earth']) # 提前计算各扇区的百分比对应关系 total_mass = df['mass'].sum() pct_map = {idx: val / total_mass * 100 for idx, val in df['mass'].items()} # 要隐藏的扇区标签 hide_label = 'Mercury' def autopct_filter(pct): # 浮点对比加误差容限,避免精度问题匹配失败 for label, target_pct in pct_map.items(): if abs(pct - target_pct) < 1e-2: return '' if label == hide_label else f'{pct:.2f}' return '' plot = df.plot.pie(y='mass', figsize=(5, 5), autopct=autopct_filter)
方法2:渲染后直接修改文本对象
这种方法更简单,不需要处理百分比匹配逻辑,饼图画完后直接定位到要隐藏的百分比文本,清空内容即可:
import pandas as pd df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], 'radius': [2439.7, 6051.8, 6378.1]}, index=['Mercury', 'Venus', 'Earth']) plot = df.plot.pie(y='mass', figsize=(5, 5), autopct= '%.2f') # 饼图的texts列表前半部分是扇区标签,后半部分是百分比数值 # Mercury是第一个扇区,对应百分比的索引等于扇区总数 hide_index = list(df.index).index('Mercury') pct_texts = plot.texts[len(df):] pct_texts[hide_index].set_text('')
内容的提问来源于stack exchange,提问作者safex
相关产品推荐
相关产品推荐

