Center two normal distribution curves Matplotlib Python

Viewed 709

I plotted two normal distribution curves on the graph as seen below:

What I generated

Using the below code:

import random
import numpy as np
import matplotlib.pyplot as plt
d1 = np.array([random.randrange(0,100) for i in range(100)])
d2 = np.array([random.randrange(0,50) for i in range(100)])
d1,d2 = np.sort(d1),np.sort(d2)
d1_mean,d1_std = np.mean(d1),np.std(d1)
d2_mean,d2_std = np.mean(d2),np.std(d2)
# y = np.repeat(15,100)
plt.figure(figsize=(8,6))
plt.plot(d1,stats.norm.pdf(d1,d1_mean,d1_std)*1000,'r')
plt.plot(d2,stats.norm.pdf(d2,d2_mean,d2_std)*1000,'b')
# plt.hlines(y,d1.min(),d1.max(),'g')
plt.title("Flattening the curve")
plt.show()

What I want to achieve is this:

What I want to achieve

The second graph is easier to plot because both the mean for both the normal distribution curves for the above graph were the same. However, I am unable to achieve the same with the graph at the very top. When I set the mean to be similar, this happens:

What I want to achieve2

Any tips on how to achieve this? Any help is much appreciated. Thank you for reading.

1 Answers

I think the easiest way to generate the two Gaussian curves would be to plug x-values in the range [-20, 20] into the Gaussian function with two different values of sigma. matplotlib will then make the boundaries of your plot [-20, 20], and it will be centered around 0.

import random
import numpy as np
import matplotlib.pyplot as plt

def gaussian(x, mu, sig):
    return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)

plt.figure(figsize=(8,6))
x_values = np.linspace(-20, 20, 200)

# generate gaussian curves with mu = 0, sigma = 5, 10
plt.plot(x_values, gaussian(x_values, 0, 5), color = 'blue')
plt.plot(x_values, gaussian(x_values, 0, 10), color = 'red')

plt.title("Flattening the curve")
plt.show()

enter image description here

Related