Table of Contents
The Chi-Square distribution is a statistical distribution commonly used in hypothesis testing and goodness-of-fit analysis. In Python, it can be plotted by first importing the necessary libraries, such as scipy and matplotlib. Then, the distribution can be generated using the scipy.stats module and plotted using the matplotlib.pyplot module. The plot can be customized with different parameters, such as the degrees of freedom and color. The resulting plot will show the probability density function of the Chi-Square distribution, which can be useful in visualizing the distribution and analyzing data.
Plot a Chi-Square Distribution in Python
To plot a Chi-Square distribution in Python, you can use the following syntax:
#x-axis ranges from 0 to 20 with .001 steps x = np.arange(0, 20, 0.001) #plot Chi-square distribution with 4 degrees of freedom plt.plot(x, chi2.pdf(x, df=4))
The x array defines the range for the x-axis and the plt.plot() produces the curve for the Chi-square distribution with the specified degrees of freedom.
The following examples show how to use these functions in practice.
Example 1: Plot a Single Chi-Square Distribution
The following code shows how to plot a single Chi-square distribution curve with 4 degrees of freedom
import numpy as np import matplotlib.pyplotas plt from scipy.statsimport chi2 #x-axis ranges from 0 to 20 with .001 steps x = np.arange(0, 20, 0.001) #plot Chi-square distribution with 4 degrees of freedom plt.plot(x, chi2.pdf(x, df=4))
You can also modify the color and the width of the line in the graph:
plt.plot(x, chi2.pdf(x, df=4), color='red', linewidth=3)
Example 2: Plot Multiple Chi-Square Distributions
The following code shows how to plot multiple Chi-square distribution curves with different degrees of freedom:
import numpy as np import matplotlib.pyplotas plt from scipy.statsimport chi2 #x-axis ranges from 0 to 20 with .001 steps x = np.arange(0, 20, 0.001) #define multiple Chi-square distributions plt.plot(x, chi2.pdf(x, df=4), label='df: 4') plt.plot(x, chi2.pdf(x, df=8), label='df: 8') plt.plot(x, chi2.pdf(x, df=12), label='df: 12') #add legend to plot plt.legend()
Feel free to modify the colors of the lines and add a title and axes labels to make the chart complete:
import numpy as np import matplotlib.pyplotas plt from scipy.statsimport chi2 #x-axis ranges from 0 to 20 with .001 steps x = np.arange(0, 20, 0.001) #define multiple Chi-square distributions plt.plot(x, chi2.pdf(x, df=4), label='df: 4', color='gold') plt.plot(x, chi2.pdf(x, df=8), label='df: 8', color='red') plt.plot(x, chi2.pdf(x, df=12), label='df: 12', color='pink') #add legend to plot plt.legend(title='Parameters') #add axes labels and a title plt.ylabel('Density') plt.xlabel('x') plt.title('Chi-Square Distributions', fontsize=14)
Refer to the for an in-depth explanation of the plt.plot() function.