<p>听起来你要找的是一个<a href="https://en.wikipedia.org/wiki/Multivariate_normal_distribution" rel="nofollow noreferrer">Multivariate Normal Distribution</a>。这在scipy中实现为<a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.multivariate_normal.html" rel="nofollow noreferrer">scipy.stats.multivariate_normal</a>。重要的是要记住,你要传递一个协方差矩阵给函数。所以为了简单起见,将非对角元素保留为零:</p>
<pre><code>[X variance , 0 ]
[ 0 ,Y Variance]
</code></pre>
<p>下面是一个使用此函数并生成结果分布的三维绘图的示例。我添加了colormap以使查看曲线更容易,但可以随意删除它。</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D
#Parameters to set
mu_x = 0
variance_x = 3
mu_y = 0
variance_y = 15
#Create grid and multivariate normal
x = np.linspace(-10,10,500)
y = np.linspace(-10,10,500)
X, Y = np.meshgrid(x,y)
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X; pos[:, :, 1] = Y
rv = multivariate_normal([mu_x, mu_y], [[variance_x, 0], [0, variance_y]])
#Make a 3D plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, rv.pdf(pos),cmap='viridis',linewidth=0)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()
</code></pre>
<p>给你这个情节:
<a href="https://i.stack.imgur.com/NXF9g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NXF9g.png" alt="enter image description here"/></a></p>
<h2>Matplotlib v2.2不赞成使用下面的编辑,并将在v3.1中删除</h2>
<p><strike>通过<a href="http://matplotlib.org/api/mlab_api.html#matplotlib.mlab.bivariate_normal" rel="nofollow noreferrer">matplotlib.mlab.bivariate_normal</a>提供更简单的版本
它接受以下参数,因此不必担心矩阵
<code>matplotlib.mlab.bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0)</code>
这里X和Y再次是网格网格的结果,因此使用它重新创建上面的绘图:</strike></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import bivariate_normal
from mpl_toolkits.mplot3d import Axes3D
#Parameters to set
mu_x = 0
sigma_x = np.sqrt(3)
mu_y = 0
sigma_y = np.sqrt(15)
#Create grid and multivariate normal
x = np.linspace(-10,10,500)
y = np.linspace(-10,10,500)
X, Y = np.meshgrid(x,y)
Z = bivariate_normal(X,Y,sigma_x,sigma_y,mu_x,mu_y)
#Make a 3D plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z,cmap='viridis',linewidth=0)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()
</code></pre>
<p>给予:
<a href="https://i.stack.imgur.com/AoyVX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AoyVX.png" alt="enter image description here"/></a></p>