python pylab plot normal distribution

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

Given a mean and a variance is there a simple pylab function call which will plot a normal distribution?

Or do I need to make one myself?

回答1:

import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab import math  mu = 0 variance = 1 sigma = math.sqrt(variance) x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100) plt.plot(x,mlab.normpdf(x, mu, sigma)) plt.show() 



回答2:

I don't think there is a function that does all that in a single call. However you can find the Gaussian probability density function in scipy.stats.

So the simplest way I could come up with is:

import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm  # Plot between -10 and 10 with .001 steps. x_axis = np.arange(-10, 10, 0.001) # Mean = 0, SD = 2. plt.plot(x_axis, norm.pdf(x_axis,0,2)) 

Sources:



回答3:

Unutbu answer is correct. But becouse our mean can be more or less than zero I would still like to change this :

x = np.linspace(-3 * sigma, 3 * sigma, 100) 

to this :

x = np.linspace(-3 * sigma + mean, 3 * sigma + mean, 100) 


回答4:

If you prefer to use a step by step approach you could consider a solution like follows

import numpy as np import matplotlib.pyplot as plt  mean = 0; std = 1; variance = np.square(std) x = np.arange(-5,5,.01) f = np.exp(-np.square(x-mean)/2*variance)/(np.sqrt(2*np.pi*variance))  plt.plot(x,f) plt.ylabel('gaussian distribution') plt.show() 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!