8

So I want to plot a normal distribution, and I've seen one way to do this is by using this code:

import numpy as np
import matplotlib.pyplot as plt

mu = 5
sigma = 1

s = np.random.normal(mu, sigma, 1000)

count, bins, ignored = plt.hist(s, 100, normed=True);
pdf = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp(- (bins - mu)**2 / (2 * sigma**2))

mu_ = 10
sigma_ = 1
s = np.random.normal(mu_, sigma_, 1000)

count_, bins_, ignored_ = plt.hist(s, 100, normed=True);
pdf_ = 1/(sigma_ * np.sqrt(2 * np.pi)) * np.exp(- (bins_ - mu_)**2 / (2 * sigma_**2))

plt.plot(bins, pdf, linewidth=2, color='g')
plt.plot(bins_, pdf_, linewidth=2, color='r')

plt.show()

And the result is:

enter image description here

My question is, can I somehow hide the histogram plot so only the normal distribution line is shown?? I know there is another way to plot normal distribution, but I kinda prefer this way

Thank you for the help!!!

Pramod Gharu
  • 1,105
  • 3
  • 9
  • 18
KaraiKare
  • 155
  • 1
  • 2
  • 10

2 Answers2

14

One possible way of obtaining slices of apples is of course to prepare an apple pie and later pick all the apples from the pie. The easier method would surely be not to make the cake at all.

So, the obvious way not to have a histogram plot in the figure is not to plot it in the first place. Instead, calculate the histogram using numpy.histogram (which is anyways the function called by plt.hist), and plot its output to the figure.

import numpy as np
import matplotlib.pyplot as plt

mu = 5
sigma = 1

s = np.random.normal(mu, sigma, 1000)

count, bins  = np.histogram(s, 100, normed=True)
pdf = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp(- (bins - mu)**2 / (2 * sigma**2))

mu_ = 10
sigma_ = 1
s = np.random.normal(mu_, sigma_, 1000)

count_, bins_  = np.histogram(s, 100, normed=True)
pdf_ = 1/(sigma_ * np.sqrt(2 * np.pi)) * np.exp(- (bins_ - mu_)**2 / (2 * sigma_**2))

plt.plot(bins, pdf, linewidth=2, color='g')
plt.plot(bins_, pdf_, linewidth=2, color='r')

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 1
    Wow and it always irked me that you had to actually plot a histogram first even if you're only interested in the empirical probability distribution. Cool trick. – ToniAz Aug 02 '18 at 14:22
6

Try adding plt.clf() right before:

plt.plot(bins, pdf, linewidth=2, color='g')
plt.plot(bins_, pdf_, linewidth=2, color='r')

This will clear the histogram, while still allowing you to use the output from it being drawn. If you'd like to have two separate figures, one with histogram and one with lines, add plt.figure() instead of plt.clf().

Christopher Shroba
  • 7,006
  • 8
  • 40
  • 68