Skip to main content
 首页 » 编程设计

python之Matplotlib 直方图之绘制大于给定值的值

2024年10月24日14grandyang

我有以下直方图:

它是用这段代码生成的:

import matplotlib.pyplot as plt 
import numpy as num 
 
 
treshold_file='false_alarms.txt' 
with open(treshold_file, 'r') as f2: 
    lines = f2.readlines() 
data = [line.split() for line in lines] 
data1 = num.array(data) 
data2= data1.astype(float) 
plt.hist((data2), alpha=0.4,bins=[100,110,120,130,   140,150,160,180,200,250,300,350,400]) 
plt.xlabel("treshold") 
plt.ylabel("Frequency") 

我想为每个 bin 绘制大于或等于给定阈值的值的数量。

对于 bin 100,我想绘制样本数量 > 100,等等。

请您参考如下方法:

在构建必要的数据后,我会使用手动 bar 绘图:

import numpy as np 
import matplotlib.pyplot as plt 
 
# dummy data 
data2 = np.random.randint(low=0, high=450, size=200) 
 
bins = [100,110,120,130,140,150,160,180,200,250,300,350,400] 
bincenters = (np.array(bins)[1:] + bins[:-1])/2 
binwidths = np.diff(bins) 
binvals = [np.sum(data2>=thresh) for thresh in bins[:-1]] 
 
fig, ax = plt.subplots() 
ax.bar(bincenters, binvals, width=binwidths, alpha=0.4, 
       edgecolor=['darkblue']) 
ax.set_xlabel('threshold') 
ax.set_ylabel('occurences') 
ax.autoscale('x', tight=True) 
 
plt.show() 

结果:

数组 bins 实际上是阈值列表 (ndarray)。对于每个阈值,我们计算高于阈值的 data2 值的数量,这些是条形图的值,称为 binvals。我们跳过最后的索引,以在输出中获得正确的维度。辅助数组 bincenters 包含每个 bin 的中点(通过取两个对应边的平均值)。