4 C
London
Friday, December 20, 2024
HomePythonData Visualizations in PythonHow to Make a Bell Curve in Python

How to Make a Bell Curve in Python

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

A “bell curve” is the nickname given to the shape of a normal distribution, which has a distinct “bell” shape:

Bell curve in Python

This tutorial explains how to make a bell curve in Python.

How to Create a Bell Curve in Python

The following code shows how to create a bell curve using the numpy, scipy, and matplotlib libraries:

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

#create range of x-values from -4 to 4 in increments of .001
x = np.arange(-4, 4, 0.001)

#create range of y-values that correspond to normal pdf with mean=0 and sd=1 
y = norm.pdf(x,0,1)

#define plot 
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(x,y)

#choose plot style and display the bell curve 
plt.style.use('fivethirtyeight')
plt.show()

Bell curve in Python

How to Fill in a Bell Curve in Python

The following code illustrates how to fill in the area under the bell curve ranging from -1 to 1:

x = np.arange(-4, 4, 0.001)
y = norm.pdf(x,0,1)

fig, ax = plt.subplots(figsize=(9,6))
ax.plot(x,y)

#specify the region of the bell curve to fill in 
x_fill = np.arange(-1, 1, 0.001)
y_fill = norm.pdf(x_fill,0,1)
ax.fill_between(x_fill,y_fill,0, alpha=0.2, color='blue')

plt.style.use('fivethirtyeight')
plt.show()

Bell curve with area filled in Python

Note that you can also style the graph in any way you’d like using the many matplotlib styling options. For example, you could use a “solar light” theme with a green line and green shading:

x = np.arange(-4, 4, 0.001)
y = norm.pdf(x,0,1)

fig, ax = plt.subplots(figsize=(9,6))
ax.plot(x,y, color='green')

#specify the region of the bell curve to fill in 
x_fill = np.arange(-1, 1, 0.001)
y_fill = norm.pdf(x_fill,0,1)
ax.fill_between(x_fill,y_fill,0, alpha=0.2, color='green')

plt.style.use('Solarize_Light2')
plt.show()

Normal distribution curve in Python with matplotlib

You can find the complete style sheet reference guide for matplotlib here.

Additional Resources

How to Make a Bell Curve in Excel

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories