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

Matplotlib图例显示问题:饼图需展示DataFrame中未出现的分类

解决饼图图例始终显示指定分类的问题

我来帮你搞定这个饼图图例的问题!核心痛点就是当DataFrame里缺少某个分类时,默认的value_counts()只会统计存在的项,导致图例少了对应的分类,颜色也没法对应上。下面给你两种实用的解决方案,按需选择:

方案一:显示0%占比,完整保留所有分类

这种方法会把缺失的分类补全为0计数,饼图里会显示该分类的0%占比,图例自然就包含两个指定分类了,颜色也能精准对应:

import pandas as pd
import matplotlib.pyplot as plt

# 示例DataFrame(这里模拟只有'Passed'的情况)
df_spark = pd.DataFrame({'Missing_records_check': ['Passed', 'Passed', 'Passed']})

# 定义需要显示的所有分类和对应颜色
target_categories = ['Passed', 'Failed']
category_colors = ['green', 'red']

# 补全缺失分类的计数,不存在的分类填充0
full_counts = df_spark['Missing_records_check'].value_counts()\
    .reindex(target_categories, fill_value=0)

# 绘制饼图
ax_3 = full_counts.plot(
    kind='pie',
    figsize=(10, 10),
    legend=True,
    autopct='%1.1f%%',
    startangle=90,
    shadow=False,
    colors=category_colors,
    labels=target_categories  # 指定标签为我们的目标分类,确保图例显示正确
)

plt.show()

关键步骤解释:

  • reindex(target_categories, fill_value=0):这是核心操作,它会按照我们指定的分类列表重新排序并补全,不存在的分类会被填充为0,这样饼图的数据源就包含了两个分类。
  • colors=category_colors:颜色列表和分类列表顺序一一对应,保证'Passed'是绿色,'Failed'是红色。

方案二:不显示0%占比,但图例仍保留所有分类

如果不想在饼图里显示0%的空白部分,只展示有数据的分类,但图例还是要完整显示两个选项,可以用手动创建图例元素的方式:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

# 示例DataFrame(模拟只有'Failed'的情况)
df_spark = pd.DataFrame({'Missing_records_check': ['Failed', 'Failed']})

# 定义目标分类和对应颜色
target_categories = ['Passed', 'Failed']
category_colors = ['green', 'red']

# 只统计有数据的分类
filtered_counts = df_spark['Missing_records_check'].value_counts()

# 绘制饼图时不自动生成图例
ax_3 = filtered_counts.plot(
    kind='pie',
    figsize=(10, 10),
    legend=False,
    autopct='%1.1f%%',
    startangle=90,
    shadow=False,
    # 只给有数据的分类匹配对应颜色
    colors=[category_colors[target_categories.index(cat)] for cat in filtered_counts.index]
)

# 手动创建图例元素,确保两个分类都显示
legend_elements = [
    Patch(facecolor=category_colors[i], label=target_categories[i]) 
    for i in range(len(target_categories))
]
ax_3.legend(handles=legend_elements, loc='upper right')

plt.show()

关键步骤解释:

  • 先过滤掉计数为0的分类,只绘制有数据的部分。
  • 使用Patch创建自定义图例元素,直接指定每个分类的颜色和标签,这样不管饼图里有没有该分类,图例都会完整显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:10:48