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

如何移除pandas饼图中占比低于4%的百分比标签?

问题描述

我有一个规模较大的DataFrame(示例数据如下):

import pandas as pd

# 示例数据
df = pd.DataFrame({
    'title_of_the_novel': ['Beasts and creatures', 'Monsters', 'At risk', 'Manuela and Ricardo', 'War against the machine'],
    'author': ['Bruno Ivory', 'Renata Mcniar', 'Charles Dobi', 'Lucas Zacci', 'Angelina Trotter'],
    'publishing_year': [1850, 1866, 1870, 1889, 1854],
    'mentioned_cities': ['London', 'New York', 'New York', 'Rio de Janeiro', 'Paris']
})

# 筛选1880-1890年的数据
df_1880_1890 = df[(df['publishing_year'] >= 1880) & (df['publishing_year'] <= 1890)]

我已通过以下代码绘制饼图,但由于数据量大,部分扇区的占比仅为0.5%或1%,需要移除所有占比低于4%的百分比标签:

# 原绘图代码
1880s_data = df_1880_1890.groupby(['mentioned_cities']).sum().plot(
    kind='pie', y='publishing_year', autopct='%1.1f%%', radius=12, ylabel='', shadow=True)

1880s_data.legend().remove()

1880s_data_image = 1880s_data.get_figure()
1880s_data_image.savefig("1880s_pie_chart.pdf", bbox_inches='tight')
解决方案

要实现只显示占比≥4%的标签,需要自定义一个函数来控制autopct的输出,替代默认的格式化字符串:

import pandas as pd

# 自定义百分比过滤函数:仅显示占比≥4%的标签
def filter_autopct(pct):
    return f'{pct:.1f}%' if pct >= 4 else ''

# 先计算分组汇总数据,让逻辑更清晰
grouped_data = df_1880_1890.groupby(['mentioned_cities'])['publishing_year'].sum()

# 绘制饼图,使用自定义的autopct函数
ax = grouped_data.plot(
    kind='pie', autopct=filter_autopct, radius=12, ylabel='', shadow=True
)

ax.legend().remove()

# 保存图片
fig = ax.get_figure()
fig.savefig("1880s_pie_chart.pdf", bbox_inches='tight')

关键说明:

  • filter_autopct函数会接收每个扇区的占比数值pct,当占比≥4%时返回格式化后的百分比字符串,否则返回空字符串,这样低占比的扇区就不会显示标签。
  • 先单独计算分组汇总数据,既提升代码可读性,也避免绘图过程中重复计算。
  • 只需将原代码中的autopct='%1.1f%%'替换为自定义函数autopct=filter_autopct即可完成需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:18:26