如何使用 Matplotlib 绘制 collections.Counter 直方图?
matplotlibpythondata visualization更新于 2025/7/12 8:44:17
要绘制直方图,使用 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()
输出

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/
打印
下一节:一次性将所有打开的 Matplotlib 图形保存在一个文件中 ❯❮ 上一节:如何显示 Seaborn pairplot() 或 PridGrid() 图表的标题?(Matplotlib)

