1

I'm trying to graph the standard deviations on a matplotlib graph, similar to http://en.wikipedia.org/wiki/File:Standard_deviation_diagram.svg

So far, I've managed to draw the curve:

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)

But I'm having difficulty rewriting this R function into 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
}

So far, I've got this:

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])

But I've got the coordinates in the Polygon() call wrong somehow, as I get:

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

1 Answer 1

1

The problem is that the argument to plt.Polygon should be a list of 2D tuples so try this:

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.