plot a normal distribution in python

To plot a normal distribution in Python, we can use the scipy.stats module to generate samples from the distribution and then use matplotlib to visualize the distribution.

Here is an example code snippet:

main.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# Create a range of x-values
x = np.linspace(-3, 3, 1000)

# Generate samples from a normal distribution
samples = norm.pdf(x, loc=0, scale=1)

# Plot the distribution
plt.plot(x, samples)

# Add labels and a title
plt.xlabel('x')
plt.ylabel('PDF')
plt.title('Normal Distribution')

# Show the plot
plt.show()
391 chars
21 lines

In this code, we first create a range of x-values using numpy.linspace. We then generate samples from a normal distribution using the norm.pdf function from scipy.stats, which takes the loc (mean) and scale (standard deviation) as arguments. Finally, we use matplotlib.pyplot.plot to plot the distribution and add labels and a title.

The resulting plot should show a bell-shaped curve centered at zero with a spread of one standard deviation.

gistlibby LogSnag