gpt4 book ai didi

python - 向直方图线添加 0 个起始值和结束值 (matplotlib)

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:24 25 4
gpt4 key购买 nike

我想让这条线叠加在这个直方图上,使其两端都为零。我假设将 0 值添加到数据数组的开头和结尾就足够了,但这似乎不起作用。

plot

plt.style.use('seaborn-white')
data = np.array(sizes_)
n, bins, _ = plt.hist(data, bins=bins, alpha=0.2, density=True)
plt.grid(axis='y', alpha=0.5)
plt.xlim([0, 500])
bin_centers = 0.5 * (bins[1:] + bins[:-1])

## Tried this but doesn't work
np.insert(bin_centers, 0, 0)
np.append(bin_centers, 500)
np.insert(n, 0, 0)
np.append(n, 0)
##

plt.plot(bin_centers, n)
plt.xlabel('length (nts)')
plt.ylabel('frequency')
plt.title('Length Distribution')
plt.savefig(outfile)

有什么想法可以做到这一点吗?

最佳答案

插入后需要保存数组。此外,您需要在数组末尾附加一对 x-y 值。由于您没有提供 MCVE,以下是使用示例数据集执行此操作的一种方法

plt.style.use('seaborn-white')
np.random.seed(121)
sizes_ = np.random.randint(2, 100, 50)
data = np.array(sizes_)
n, bins, _ = plt.hist(data, bins=20, alpha=0.2, density=True)
plt.grid(axis='y', alpha=0.5)
bin_centers = 0.5 * (bins[1:] + bins[:-1])

bin_diff = np.diff(bin_centers)[-1]

bin_centers = np.insert(bin_centers, 0, 0)
bin_centers = np.insert(bin_centers, len(bin_centers), bin_centers[-1] + bin_diff)

n = np.insert(n, 0, 0)
n = np.insert(n, len(n), 0)

plt.plot(bin_centers, n)
plt.xlabel('length (nts)')
plt.ylabel('frequency')
plt.title('Length Distribution')

enter image description here

关于python - 向直方图线添加 0 个起始值和结束值 (matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201689/

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