如何使用布尔值筛选DataFrame并绘制过滤数据的分类占比饼图
饼图实现方案
你原有代码存在变量名不统一的小问题:定义的筛选变量为filter,后续打印时调用了不存在的filtered_1,调整后引入matplotlib绘图库即可实现需求,完整可运行代码如下:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 解决matplotlib中文显示乱码问题,Windows环境可直接使用,其他系统可替换为对应中文字体名 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 原始数据集构造 data = {'City': ['KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'ACCRA'], 'Building': ['Commercial', 'Commercial', 'Industrial', 'Commercial', 'Industrial', 'Commercial', 'Commercial', 'Commercial', 'Commercial'], 'LPL': ['NC', 'C', 'C', 'C', 'NC', 'C', 'NC', 'NC', 'NC'], 'Lgfd': ['NC', 'C', 'C', 'C', 'NC', 'C', 'NC', 'NC', 'C'], 'Location': ['NC', 'C', 'C', 'C', 'NC', 'C', 'C', 'NC', 'NC'], 'Hazard': ['NC', 'C', 'C', 'C', 'NC', 'C', 'C', 'NC', 'NC'], 'Inspection': ['NC', np.nan, np.nan, np.nan, 'NC', 'NC', 'C', 'C', 'C'], 'Name': ['Zonal', 'In Prog', 'Tullow Oil', 'XGI', 'Food Factory', 'MOH', 'EV', 'CSD', 'Electroland'], 'Air Termination System': ['Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Early Streamer Emission', 'Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Early Streamer Emission'], 'Positioned Using': ['Highest Points', 'Software', 'Software', 'Software', 'Highest Points', np.nan, np.nan, 'Rolling Sphere Method', 'Software']} df = pd.DataFrame(data) # 计算两类数据的行数 both_c_count = len(df[(df["LPL"] == "C") & (df["Hazard"] == "C")]) other_count = len(df) - both_c_count count_list = [both_c_count, other_count] label_list = ['LPL和Hazard均为C', 'LPL和Hazard不同时为C'] # 绘制饼图:autopct参数控制百分比显示格式,保留1位小数 plt.pie(count_list, labels=label_list, autopct='%1.1f%%') # 确保饼图为正圆形 plt.axis('equal') # 添加图标题 plt.title('两类数据占总样本比例') # 显示图像 plt.show()
参数说明
autopct='%1.1f%%':设置饼图上显示的百分比格式,可根据需求调整小数位数,比如改为%1.0f%%就是只显示整数百分比plt.rcParams相关配置:仅用于解决中文标签乱码问题,如果你不需要显示中文或者运行环境不需要可以删除该部分代码
内容的提问来源于stack exchange,提问作者Kwaku Biney
相关产品推荐
相关产品推荐

