【问题标题】:Why the mean is not centered at 0 and 1 respectively for both the graphs?为什么两个图的均值不分别以 0 和 1 为中心?
【发布时间】:2020-02-11 21:07:35
【问题描述】:

下面是代码:

import numpy as np 
import matplotlib.pyplot as plt 
a1 = np.random.normal(loc=0,scale=2,size=1000) 
h1, b1 = np.histogram(a1,bins=10,density=True) 
plt.plot(h1, color='r') 
a2 = np.random.normal(loc=1,scale=5,size=30) 
h2, b2 = np.histogram(a1,bins=5,density=True) 
plt.plot(h2, color='g') 
plt.show()  

【问题讨论】:

  • 请考虑,为了在 2D 平面上绘制某些东西,您需要 两个 坐标,plot(x,y)
  • @ImportanceOfBeingErnest 没有找到原因。
  • 您制作了两个相同随机样本的直方图(您每次都使用a1而不是a1a2)。
  • 但原因是:你只是绘制了 bins,没有考虑这些 bins 的跨度。

标签: python-3.x numpy matplotlib


【解决方案1】:

您没有考虑垃圾箱的跨度。事实上,您甚至为 same 随机样本 a1,而不是 a1a2 的两个不同样本创建了 bin。例如,我们可以使用以下方法计算箱的中间:

>>> 0.5*(b1[:-1]+b1[1:])
array([-6.01624486, -4.69961062, -3.38297639, -2.06634215, -0.74970792,
        0.56692632,  1.88356055,  3.20019479,  4.51682903,  5.83346326])

如果我们随后绘制两个分布图,我们会看到:

import numpy as np 
import matplotlib.pyplot as plt

a1 = np.random.normal(loc=0,scale=2,size=1000) 
h1, b1 = np.histogram(a1,bins=10,density=True)
b1m = 0.5*(b1[:-1]+b1[1:])

plt.plot(b1m, h1, color='r') 
a2 = np.random.normal(loc=1,scale=5,size=30) 
h2, b2 = np.histogram(a2,bins=5,density=True)
b2m = 0.5*(b2[:-1]+b2[1:])

plt.plot(b2m, h2, color='g') 
plt.show()

然后我们看到:

【讨论】:

    猜你喜欢
    • 2015-02-23
    • 1970-01-01
    • 2022-12-01
    • 2021-11-01
    • 2021-12-05
    • 2013-06-06
    • 2023-01-19
    • 2014-07-24
    • 1970-01-01
    相关资源
    最近更新 更多