如何使用 Matplotlib 绘制 collections.Counter 直方图?


若要使用 collections.Counter 绘制直方图,我们可以使用 bar() 方法。在 bar() 方法中,我们可以使用 collections.counter() 来获得每个元素的频率。将元素及其频率作为高度。

步骤

  • 设置图片大小并调整子图之间的填充。
  • 生成一个数据点列表。
  • 使用 collections.Counter() 获取字典 d
  • 使用 d.keys()d.values() 生成柱状图。
  • 若要显示图片,请使用 show() 方法。

示例

import collections
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [0, 1, 2, 4, 1, 3, 0, 4, 1, 4, 3, 5, 6, 5, 2]

d = collections.Counter(data)

plt.bar(d.keys(), d.values())

plt.show()

输出

更新日期:2021 年 6 月 18 日

3K+ 浏览量

开启您的 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.