首页 > 解决方案 > Matplotlib:在给定预先计算的计数和 bin 的情况下绘制直方图

问题描述

我有一些数据x传递给以numpy.histogram(x)获取计数和 bin 边缘。然后我将这些保存到文件中。稍后,我想加载这些数据并绘制直方图。

我有

counts = [20, 19, 40, 46, 58, 42, 23, 10, 8, 2]
bin_edges = [0.5, 0.55, 0.59, 0.63, 0.67, 0.72, 0.76, 0.8, 0.84, 0.89, 0.93]

如何绘制此直方图?

标签: pythonnumpymatplotlib

解决方案


Pyplotbar可以在边缘对齐使用(默认居中),宽度计算如下np.diff

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

counts = np.array([20, 19, 40, 46, 58, 42, 23, 10, 8, 2])
bin_edges = np.array([0.5, 0.55, 0.59, 0.63, 0.67, 0.72, 0.76, 0.8, 0.84, 0.89, 0.93])

ax.bar(x=bin_edges[:-1], height=counts, width=np.diff(bin_edges), align='edge', fc='skyblue', ec='black')
plt.show()

结果图

可以选择将 xticks 设置为 bin 边缘:

ax.set_xticks(bin_edges)

或到垃圾箱中心:

ax.set_xticks((bin_edges[:-1] + bin_edges[1:]) / 2)

推荐阅读