Chi-Square Distribution

dakshdeepHERE's avatar
Published Mar 4, 2025
Contribute to Docs

The chi-square distribution is derived from the sum of squared standard normal variables. It plays a crucial role in statistical tests, such as the chi-square test for independence and goodness of fit. The shape of the distribution varies with its degrees of freedom; for lower degrees of freedom, it is skewed, while higher degrees of freedom result in a more symmetric shape.

Example

The example below demonstrates how to generate random samples from a chi-square distribution and visualize them with a histogram. In this demonstration, SciPy is used to generate the samples and Matplotlib is used for plotting:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import chi2
# Set the degrees of freedom
df = 4
# Generate 1,000 random samples from the chi-square distribution
data = chi2.rvs(df, size=1000)
# Plot the histogram
plt.hist(data, bins=30, density=True, alpha=0.6, color='skyblue', edgecolor='black')
plt.title(f"Chi-Square Distribution (df={df})")
plt.xlabel("Value")
plt.ylabel("Density")
plt.show()

The above code generates a histogram illustrating the chi-square distribution:

The output for the above example

All contributors

Contribute to Docs

Learn Data Science on Codecademy