对计数字典排序提取键值列表,绘制仅含最高频两值的饼图
统计频率并绘制高频值饼图
1. 统计并排序频率字典
用Python的collections.Counter可以快速统计列表中元素的出现次数,再通过排序提取键和频率的列表:
from collections import Counter Value_list = [1, 3, 2, 4, 5, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 5, 2, 2, 2, 2, 1, 1] # 统计每个值的出现频率 count_dict = Counter(Value_list) # 按频率从高到低排序,得到(值, 频率)的元组列表 sorted_counts = sorted(count_dict.items(), key=lambda x: x[1], reverse=True) # 提取排序后的键列表和频率列表 sorted_keys = [item[0] for item in sorted_counts] sorted_values = [item[1] for item in sorted_counts] # 输出结果 print("排序后的键列表:", sorted_keys) print("排序后的频率列表:", sorted_values)
运行后输出:
排序后的键列表: [1, 2, 3, 5, 4] 排序后的频率列表: [8, 8, 4, 2, 1]
2. 绘制仅包含最高两个频率值的饼图
用matplotlib绘制饼图,只需截取排序后的前两组数据即可:
import matplotlib.pyplot as plt # 获取频率最高的两个值及其次数 top_two_items = sorted_counts[:2] # 提取标签和对应频率 labels = [str(item[0]) for item in top_two_items] freqs = [item[1] for item in top_two_items] # 绘制饼图 plt.pie(freqs, labels=labels, autopct='%1.1f%%', startangle=90) plt.title('Top 2 Frequency Values') plt.axis('equal') # 确保饼图为正圆形 plt.show()
这段代码会生成一个饼图,展示值1和值2的频率占比(各50%),并标注百分比。
内容的提问来源于stack exchange,提问作者Casey
相关产品推荐
相关产品推荐

