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

如何从Matplotlib饼图中移除0%显示

如何移除饼图中的0%显示?

我明白你的困扰——当DataFrame里有0值时,matplotlib的默认饼图会把这些0%也显示出来,显得很冗余。这里有两种简单的解决方法,你可以根据需求选择:

方法一:先过滤掉0值数据(推荐)

既然那些得分为0的分类对饼图没有任何占比,直接把它们从DataFrame里过滤掉就行,这样饼图里只会显示有实际占比的部分,看起来更干净:

import matplotlib.pyplot as plt
import pandas as pd

# 你的原始DataFrame
df1 = pd.DataFrame({'score': [100.0, 0.0, 0.0]}, index=['Negative', 'Neutral', 'Positive'])

# 过滤掉score大于0的行
df_filtered = df1[df1['score'] > 0]

plt.figure(figsize=(4,3))
df_filtered.plot(kind='pie', autopct='%1.1f%%', subplots=True, startangle=90, legend = False, fontsize=14)
plt.axis('off')
plt.show()

方法二:自定义标签显示规则(保留分类但隐藏0%)

如果你非要保留这些0值分类的位置(虽然实际上它们的扇区几乎看不见),可以写一个自定义函数来控制百分比标签的显示,只显示大于0的部分:

import matplotlib.pyplot as plt
import pandas as pd

df1 = pd.DataFrame({'score': [100.0, 0.0, 0.0]}, index=['Negative', 'Neutral', 'Positive'])

# 自定义autopct函数,只输出非0的百分比
def autopct_filter(values):
    def format_label(pct):
        return '%1.1f%%' % pct if pct > 0 else ''
    return format_label

plt.figure(figsize=(4,3))
df1.plot(kind='pie', autopct=autopct_filter(df1['score']), subplots=True, startangle=90, legend = False, fontsize=14)
plt.axis('off')
plt.show()

第一种方法更实用,毕竟0值分类在饼图里没有实际意义,去掉后图表会更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:23:33