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

如何按值降序绘制Python Counter统计结果的matplotlib柱状图

问题原因
  • 你在打印Counter时看到的降序排列是Counter类的字符串格式化输出专门做的排序效果,直接调用.keys()、.values()遍历得到的元素顺序是底层字典的存储顺序(Python3.7及以后为插入顺序,更早版本完全无序),和值的降序排序规则无关。
  • 你直接截取.keys()和.values()的前10位时,两者顺序虽然在字典未修改的情况下是一一对应的,但本身就不是你需要的按值降序的顺序,所以绘制的柱状图顺序不符合预期。
解决方法

直接调用Counter内置的most_common(n)方法即可,该方法会主动返回按值降序排列的前n个(键, 值)元组,不需要手动排序。

示例代码如下:

# 取按值降序的前10组数据
top_10_items = countersum.most_common(10)
# 拆分x轴标签和y轴数值
x = [str(item[0]) for item in top_10_items]
y = [item[1] for item in top_10_items]

# 绘图
plt.bar(x, y)
plt.show()

如果需要绘制全量数据的降序柱状图,不传参数调用most_common()即可得到全部按值降序排列的键值对:

all_items = countersum.most_common()
x = [str(item[0]) for item in all_items]
y = [item[1] for item in all_items]
plt.bar(x, y)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:45:06