如何将collections Counter统计的计数列表数据展示为图表?
可视化实现方案
你可以直接基于已有Counter对象的数据,用Python常用的可视化库快速生成图表,以下是两种最常用的实现方式:
1. 静态柱状图(matplotlib实现)
适合直接生成图片保存或者嵌入报告,代码如下:
from collections import Counter import matplotlib.pyplot as plt # 替换为你自己的Counter变量即可 offset_counter = Counter({1856: 109, 1331: 4, 1351: 3, 1341: 2, 1376: 2, 1371: 2, 1356: 1, 1361: 1, 1396: 1}) # 拆分横纵坐标数据,将偏移量转成字符串避免坐标轴自动排序 x = [str(k) for k in offset_counter.keys()] y = list(offset_counter.values()) # 绘图配置 plt.figure(figsize=(10, 6)) bars = plt.bar(x, y, color='#3498db') # 每个柱子顶部标注具体次数 for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2, height, str(height), ha='center', va='bottom') plt.xlabel('有效载荷起始偏移量') plt.ylabel('出现次数') plt.title('有效载荷起始偏移量出现次数统计') plt.xticks(rotation=45) plt.tight_layout() # 执行后直接弹出图表展示,也可以调用savefig保存为本地图片 plt.show() # plt.savefig('offset_count.png', dpi=300)
2. 交互式柱状图(plotly实现)
适合需要交互查看细节的场景,生成的HTML文件可以直接在浏览器打开,支持放大缩小、悬停查看数值:
from collections import Counter import plotly.express as px import pandas as pd offset_counter = Counter({1856: 109, 1331: 4, 1351: 3, 1341: 2, 1376: 2, 1371: 2, 1356: 1, 1361: 1, 1396: 1}) # 转换为DataFrame格式供plotly读取 df = pd.DataFrame({ '偏移量': [str(k) for k in offset_counter.keys()], '出现次数': list(offset_counter.values()) }) fig = px.bar(df, x='偏移量', y='出现次数', text='出现次数', title='有效载荷起始偏移量出现次数统计') fig.update_traces(textposition='outside') fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide') # 执行后自动在浏览器打开图表,也可以保存为本地HTML文件 fig.show() # fig.write_html('offset_count.html')
可选扩展
- 如果需要展示各偏移量的占比,可以把柱状图替换为饼图、环形图
- 如果后续统计的偏移量数量较多,可以换成水平柱状图避免x轴标签重叠
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

