pyplot 的bar
可以在其边缘对齐(默认居中)使用,宽度通过以下方式计算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)