python - 使用 Matplotlib 在高斯上绘制标准差图

标签 python r matplotlib statistics

我正在尝试在 matplotlib 图上绘制标准差,类似于 http://en.wikipedia.org/wiki/File:Standard_deviation_diagram.svg

到目前为止,我已经成功绘制了曲线:

mean = 0
variance = 1
rng = 4.
sigma = sqrt(variance)
x = np.linspace(-rng, rng, (rng * 10) * 2)
plt.plot(x, normpdf(x, mean, sigma))
plt.ylim(0, (rng / 10) + 0.05)

但是我很难将这个 R 函数重写为 Python:

polysection <- function(a, b, col, n=11){
    dx <- seq(a, b, length.out=n)
    polygon(c(a, dx, b), c(0, dnorm(dx), 0), col=col, border=NA)
    # draw a white vertical line on "inside" side to separate each section
    segments(a, 0, a, dnorm(a), col="white")
}

# Build the four left and right portions of this bell curve
for(i in 0:3){
    polysection(   i, i+1,  col=cols[i+1]) # Right side of 0
    polysection(-i-1,  -i,  col=cols[i+1]) # Left right of 0
}

到目前为止,我已经得到了这个:

cols = np.array(["#2171B5", "#6BAED6", "#BDD7E7", "#EFF3FF"])

def polysection(a, b, col, n=11):
    dx = np.linspace(a, b, n)
    ax.add_patch(plt.Polygon(
            np.hstack((np.array(a), dx, np.array(b))),
            np.hstack((np.array(0), normpdf(dx, 0, 1), np.array(0)))))
    plt.plot(
        [a, 0],
        [a, normpdf(a, 0, 1)],
        color='blue')

for i in xrange(4):
    polysection(i, i+1, col=cols[i + 1]) 
    polysection(-i - 1, -i, col=cols[i + 1])

但是我在 Polygon() 调用中的坐标不知何故错误,正如我得到的:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

最佳答案

问题是 plt.Polygon 的参数应该是 2D 元组列表,所以试试这个:

xs = list(np.hstack((np.array(a), dx, np.array(b))))
ys = list(np.hstack((np.array(0), mlab.normpdf(dx, 0, 1), np.array(0))))
xy = zip(xs,ys)
ax.add_patch(plt.Polygon(xy))

关于python - 使用 Matplotlib 在高斯上绘制标准差图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21096563/

相关文章:

python - Matplotlib:图例中的颜色编码文本而不是线条

python - Python除了matplotlib之外还有其他图形模块吗?

Python ..访问默认排序功能?

python - 如何检查 python 类或对象是否是用户定义的(不是内置的)?

python - Python 中是否可以无限循环?

python - for 循环 & if 在字典中

r - 创建新的数据框,其中变量在特定时期内每年增长

r - 如何在连续的颜色图例中添加一条线而不是在图中添加一条线?

r - ggplot : how to color points different than the connecting line

python - 如何在seaborn jointgrid/jointplot中注释边际图/分布图