将0个开始和结束值添加到直方图行(matplotlib)

时间:2019-03-16 21:31:34

标签: python numpy matplotlib

我想让线叠加在该直方图上,使其两端都为零。我以为将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)

有什么想法我该怎么做?

2 个答案:

答案 0 :(得分:3)

插入后需要保存阵列。此外,您需要在数组末尾附加一对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')

https://chromium.googlesource.com/external/webrtc/+/master/sdk/android/api/org/webrtc/VideoFileRenderer.java

答案 1 :(得分:1)

np.append()np.insert()不是就地函数,它们返回结果,您应该将其分配给变量(bin_centers = np.insert(bin_centers, 0, bins[0])

import numpy as np
from matplotlib import pyplot as plt

plt.style.use('seaborn-white')
data = np.array([15, 20, 14, 10, 20, 21, 18, 8])
n, bins, _ = plt.hist(data, alpha=0.2, density=True)
plt.grid(axis='y', alpha=0.5)
plt.xlim([0, 30])
bin_centers = 0.5 * (bins[1:] + bins[:-1])

bin_centers = np.insert(bin_centers, 0, bins[0])
bin_centers = np.append(bin_centers, bins[-1])
n = np.insert(n, 0, 0)
n = np.append(n, 0)

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

enter image description here