简体   繁体   English

Matplotlib:在给定预先计算的计数和箱的情况下绘制直方图

[英]Matplotlib: Plot histogram given pre-computed counts and bins

I have some data x which I pass to numpy.histogram(x) to get the counts and bin edges.我有一些数据x传递给numpy.histogram(x)以获取计数和 bin 边缘。 I then save these to a file.然后我将这些保存到一个文件中。 Later, I want to load this data and plot the histogram.后来,我想加载这些数据并绘制直方图。

I have我有

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]

How can I plot this histogram?我怎样才能绘制这个直方图?

Pyplot's bar can be used aligned at their edge (default is centered), with widths calculated by np.diff : 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()

结果图

Optionally the xticks can be set to the bin edges:可以选择将 xticks 设置为 bin 边缘:

ax.set_xticks(bin_edges)

Or to the bin centers:或到垃圾箱中心:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM