0

I have two blocks of code and two graphs:

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math
import seaborn as sns

mu = 0
variance = 1
sigma = math.sqrt(variance) 
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()

In this first block of code I am plotting a normal distribution given the mean and standard deviation. The result is this:

Gaussian Distribution

Then I have the other block of code in order to draw a random sample from a normal distribution (in my case, but it could be any other distribution and I would be answering the same question).

value = np.random.normal(loc=mu ,scale=,size=1000)
sns.histplot(value)

Then I plot it and it's like this

Histogram of my data

I tried to write the code in the same cell but it shows only the histogram.
My question is: is it possible to "merge" the two graphs? I mean, plotting the standard normal distribution of the first block of code on top of the histogram plot, in order to have only one graph and compare visually how close your histogram is to a standard normal distribution?

Emanuele
  • 174
  • 13

1 Answers1

0

Try the below:

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
values = np.random.normal(loc=mu, scale=sigma, size=1000)
fig, ax1 = plt.subplots()
ax1.plot(x, stats.norm.pdf(x, mu, sigma), color='blue')
ax1.set_ylabel('PDF', color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
ax2 = ax1.twinx()
sns.histplot(values, ax=ax2, color='orange')
plt.show()
Abdulmajeed
  • 1,502
  • 2
  • 10
  • 13
  • Ok I have edited my answer and tried this one and it worked. – Abdulmajeed Feb 20 '23 at 12:44
  • 1
    Using a `twinx` ax here is quite ugly here. It would be much better to use `stat='density'` in the call to `sns.histplot` to scale down the histogram to have the same area of 1 as the pdf. – JohanC Feb 20 '23 at 15:24