reinhardt
reinhardt

Reputation: 2253

How to generate multiple gaussian plots?

I am trying to plot multiple gaussian plots that'll have same mean and std dev, meaning that when the first plot ends at 20, the second plot must start from 20 and end at 40 with the peak being at 30

mu = 10
sigma = 2
n = 2
x = np.linspace(0,n*20,n*20)
for i in range(0,n):
    pdf = stats.norm.pdf(x, n*mu, sigma)
    plt.plot(x, pdf)

but this gives me just one plot as Image enter image description here

What i would like to generate is:

Desired output enter image description here

Can someone please tell me the mistake that I am doing?

Upvotes: 0

Views: 1331

Answers (2)

norok2
norok2

Reputation: 26886

The issue with your code is that here:

pdf = stats.norm.pdf(x, n*mu, sigma)

you are having the same pdf being plotted as n does not change inside the loop, you probably want to use i instead of n. Except that it would not work because i takes value 0 and 1 and hence mu gets to be 0 and 20 and you would need to fix also that. For a generally cleaner approach have a look at the other answer.

Upvotes: 0

Diziet Asahi
Diziet Asahi

Reputation: 40667

First, your two gaussians do not have the same means, since one is at 10 and the other at 30.

Second, you are actually creating one one gaussian, with mean at n*mu=20. If you need to generate multiple gaussians, you'll have to call norm.pdf several times, e.g. in a loop:

mus = [10,30]
sigmas = [2,2]
x = np.linspace(0,40,100)
pdf = np.zeros(shape=x.shape)
for m,s in zip(mus,sigmas):
    pdf += stats.norm.pdf(x, m, s)
plt.plot(x, pdf)

enter image description here

Upvotes: 2

Related Questions