# Plotting a Gaussian in Python

I am trying to plot a histogram of my data, and I seem to be a little confused here. I am using matplotlib in Python. Here is the code from their website:

mu = 100 #mean
sigma = 15 #std deviation
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)


I am confused as to what the x-axis should be for my use. I have calculated the standard deviation and the mean, but I am uncertain if I should replace the np.random.randn(10000) with the actual data.

It sounds like what you want to do is completely replace x in the plotting function with your data, so what you should get looks like this:

n, bins, patches = plt.hist(my_data, num_bins, normed=1, facecolor='green', alpha=0.5)
plt.show()


Also, if you aren't planning on using n, bins, or patches you can discard them by just running:

plt.hist(my_data, num_bins, normed=1, facecolor='green', alpha=0.5)
plt.show()


If this isn't correct please let me know and I'll be happy to help.

• Did everything work out for you? – Henry Hammond Jul 31 '14 at 19:13
• yes, I am able to interpret my data now. Just one last question, when I plot this, what will go on the y-axis? It looks like it may be what portion of my data a certain bin will fall in. – alex Jul 31 '14 at 19:15
• Because you have normed=1 matplotlib will normalize the y-axis to represent what percentage of your data fell in that bin. If you want the counts for each bin you can simply remove the whole normed argument. – Henry Hammond Jul 31 '14 at 19:16
• I see. this makes sense. My data is just looking odd. Median ~29 and mean~119 – alex Jul 31 '14 at 19:22
• I looked into it and my above comment is incorrect. From the Numpy docs > If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1 – Henry Hammond Jul 31 '14 at 19:24

The code you proposed for generating random numbers will not generate a distribution centered on mean and with a standard deviation sigma, as your variable names suggest. Note that if you calculate using

np.std(np.random.randn(10000))


you'll get something around 0.28 and the reason is simple: np.random.randn(k) draws k numbers between 0 and 1. To generate a vector with 10 000 numbers following a gaussian distribution of parameters mu and sigma use

from random import gauss
x=[gauss(mu, sigma) for i in range(10000)]


for which in the last line I used the "pythonic" condensed version of a for loop, the list comprehension. Then you can feed your x vector to the histogram plotting routine, that will calculate the histogram of a vector for plotting.