Python:具有范围的直方图,但是为整个集合计算分布

问题描述 投票:-1回答:2

我正在使用matplotlib绘制pdf直方图,并且由于图形的外观需要使用范围变量。在开始和结束时得到一个高点,这些峰值的概率几率要高得多,因此无法看到图表的其余部分所以我需要使用范围来“缩放”。但是当使用范围时概率密度只会考虑范围内的数据。

有没有办法继续使用范围,但概率密度不仅计算在给定范围内的数据,还计算所有数据?

提前致谢!

编辑:我正在绘制数据集的数据包大小的pdf。该图在下部区域~100字节中具有峰值,在上部区域具有~1450字节。为了显示数据集中间的分布,我使用范围来放大不同的区域,从而为分布提供更好的细节。

ax.hist(x=list_of_pkt_sizes,bins=25,density=True,range=[500,1000])

这是用于绘制其中一个放大区域的代码段示例。如上所述,它现在仅显示给定范围的分布。我想要整体发行。

python matplotlib histogram probability-density
2个回答
1
投票

不是最优雅的解决方案,但您可以很容易地手动规范化:

import numpy as np

# Convert list to numpy array for convenience
pkt_arr = np.array(list_of_pkt_sizes)

# Set range variables
min_range, max_range = 500, 1000

# Filter out elements not in range to new array
pkt_arr_in_range = pkt_arr[(pkt_arr > min_range) & (pkt_arr < max_range)]

# Get normalisers - bin size and total number of elements
num_elem_norm = pkt_arr.shape[0]
counts, bins = np.histogram(x=pkt_arr_in_range, bins=25)
bin_width = bins[1] - bins[0]

# Get x coordinates of LHS of bins
xs = bins[:-1]

# Normalise counts (prob density per unit of input)
counts_norm = counts / (num_elem_norm * bin_width)

# Use bar chart
ax.bar(xs, counts_norm, width=bin_width, align='edge')

更新:@DizietAsahi在评论中提出了更好的建议:

min_range, max_range = 500, 1000
min_all, max_all = min(list_of_pkt_sizes), max(list_of_pkt_sizes)
range_ratio = (max_all - min_all) / (max_range - min_range)
ax.hist(list_of_pkt_sizes, bins=int(round(25 * range_ratio)), density=True)
plt.xlim(min_range, max_range)

0
投票

以下是我将如何解决这个问题。我根据您的信息生成了一个包含大量低值和高值的虚假分发

plt.figure()
plt.hist(l1, density=True, bins=25)

enter image description here

我使用numpy.histogram函数来获得密度分布。请注意,我使用自定义bins=参数:我请求0-500之间的一个bin,500和1000之间的25个bin以及1000到2000之间的1个bin

p,b = np.histogram(l1, density=True, bins=[0]+list(np.linspace(500,1000,25+1))+[2000])

enter image description here

最后,我使用matplotlib的bar()函数绘制结果直方图,但我只是省略了第一个和最后一个bin

plt.figure()
plt.bar(x=b[1:-2], height=p[1:-1], width=20, align='edge')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.