设置Matplotlib直方图的高度

时间:2018-11-28 21:34:02

标签: python matplotlib

我在更改直方图条形图的高度时遇到问题。

我有以下直方图:

x = [1,2,
     11,12,
     21,22,
     31,32,33,34,35,
     41,42,43,44,45,46,47,48,
     51,52,53,54,55,56,57,58,59,
     61,62,63,64,65,66,
     71,72,73,74,75,67,
     81,82,83,
     91,92,
     101]
num_bins = [0,3,10,30,40,50,65,80,90,100]  

n, x,_ = plt.hist(x, num_bins)
plt.show()

Random Histogram

对于相同的数据,我想创建具有相同箱宽的直方图,但是每个条的高度应更改为条的总高度除以其箱宽。

因此,例如,第一个条形的总高度为2,其条带宽度为3。因此,新条带的高度应为2/3,宽度仍为3,依此类推。

非常感谢您!

2 个答案:

答案 0 :(得分:2)

基本上,您正在寻找归一化的直方图。这可以通过density参数来实现。但是,它将标准化为1。相反,您正在寻找对数据总数的规范化。因此,您可以将归一化的直方图乘以数组x的长度。

import numpy as np
import matplotlib.pyplot as plt
x = [1,2,
     11,12,
     21,22,
     31,32,33,34,35,
     41,42,43,44,45,46,47,48,
     51,52,53,54,55,56,57,58,59,
     61,62,63,64,65,66,
     71,72,73,74,75,67,
     81,82,83,
     91,92,
     101]
num_bins = [0,3,10,30,40,50,65,80,90,100]  

n, bins  = np.histogram(x, num_bins, density=True)
plt.bar(bins[:-1], n*len(x), align="edge", width=np.diff(bins), ec="k")
plt.show()

enter image description here

答案 1 :(得分:1)

Promise返回矩形对象的列表(使用变量it("handle search function", async () => { // make the test function async ... const mockHandleSearch = jest.fn(postcode => { console.log("mockHandleSearch called"); return getPostcodeDetails("abc").then(instance.handleResponse); // return the Promise }); instance.handleSearch = mockHandleSearch; await mockHandleSearch.call(instance); // await the returned Promise expect(instance.handleResponse).toBeCalled(); // SUCCESS }); 命名)。您可以修改这些对象的高度:

plt.hist

enter image description here