gpt4 book ai didi

python - 如何在 Python 中绘制具有可变宽度 bin 的直方图?

转载 作者:行者123 更新时间:2023-12-04 04:02:14 27 4
gpt4 key购买 nike

假设我有数据[1,2,3, 7,8,9,9, 20,30,40,100,1000],我想用 Python 为其绘制直方图。我关心的所有 bin 是 [0,5]、[5,10] 和 [10, +∞)。我该怎么做?

当然,以下不会这样做。

import matplotlib.pyplot as plt

data = [1,2,3, 7,8,9,9, 20,30,40,100,1000]
plt.figure()
plt.hist(data, bins=5, color="rebeccapurple")
plt.show()

最佳答案

如果强制显示具有自定义 x 范围的直方图,您可能需要先处理您的数据。

我制作了一个范围列表和 x_ticklabels 以显示带有范围的 x 轴。

import matplotlib.pyplot as plt
import numpy as np

data = [1,2,3, 7,8,9,9, 20,30,40,100,1000,500,200]
data = np.array(data)
bin_range = [
[0, 5],
[5, 10],
[10, 10000] # enough number to cover range
]

data2plot = np.zeros(len(bin_range))

for idx, (low, high) in enumerate(bin_range):
data2plot[idx] = ((low <= data) & (data < high)).sum()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(range(len(bin_range)), data2plot)

x_labels = [
f"{low}~{high}" for idx, (low, high) in enumerate(bin_range)
]

ax.set_xticks(range(len(bin_range)))
ax.set_xticklabels(x_labels)
plt.show()

enter image description here

关于python - 如何在 Python 中绘制具有可变宽度 bin 的直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62907801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com