下面是一个正态分布的例子,介绍的很详细,通过对引用函数的改变还可以绘制诸如卡方分布,t分布等常见分布函数的绘制。
如需其他分布函数代码,可以查看我上传的代码文件,里面还包括了柯布-道格拉斯函数三维分布的函数图像。
Let 𝑋 be a random variable that follows the normal distribution, i.e.,
𝑋∼𝑁(𝑎,𝑏2),X∼N(a,b2),
where 𝑎 is the mean of X, and 𝑏 is the standard deviation of 𝑋.
- Plot the probability density function of 𝑋X when 𝑎=0a=0 and 𝑏=1,2,4b=1,2,4.
- Plot the cumulative distribution function of 𝑋X when 𝑎=0a=0 and 𝑏=1,2,4b=1,2,4.
-
#第一问 import numpy as np from scipy import stats import matplotlib.pyplot as plt mean=0 #定义函数:stats.norm(a,b)为正态分布的函数;stats.chi2为卡方分布的函数;stats.t为T分布的函数 normalDistribution=stats.norm(mean,1) #标准差=2的正态分布 normalDistribution1=stats.norm(mean,2) #标准差=4的正态分布 normalDistribution2=stats.norm(mean,4) #画坐标轴,x轴从-5到5每隔0.1取一次 x=np.arange(-5,5,0.1) #列出函数表达式,(定义的函数后加.pdf代表求概率密度函数,加.cdf代表求累计函数) y=normalDistribution.pdf(x) y1=normalDistribution1.pdf(x) y2=normalDistribution2.pdf(x) #画图函数plt.plot(横坐标,纵坐标,‘颜色(r红色,b绿色)和线性(--代表虚线)’,图例=“线的含义”), plt.plot(x,y,label="standard deviation") plt.plot(x,y1,'r--',label="std=2") plt.plot(x,y2,'b--',label="std=4") #x,y轴的标注 plt.xlabel("x") plt.ylabel("probability density") #图的标题 plt.title("Normal distribution") #显示图例 plt.legend() #显示图像 plt.show() #第二问 mean=0 #标准正太分布 normalDistribution=stats.norm(mean,1) #标准差=2的正态分布 normalDistribution1=stats.norm(mean,2) #标准差=4的正态分布 normalDistribution2=stats.norm(mean,4) x=np.arange(-5,5,0.1) y=normalDistribution.cdf(x) y1=normalDistribution1.cdf(x) y2=normalDistribution2.cdf(x) plt.plot(x,y,label="standard deviation") plt.plot(x,y1,'r--',label="std=2") plt.plot(x,y2,'b--',label="std=4") plt.xlabel("x") plt.ylabel("probability density") plt.title("Normal distribution") plt.legend() plt.show()