Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

python - Illustrating Normal Distribution using Numpy, Matploblib 3D from MATLAB code

I am trying to plot normal distribution in 3D. I have a code written in MATLAB, but I have been failed to write it in Python.

The completed MATLAB's code is:

dsig = 0.25;
dx = 0.5;
mu = 0;
[X, SIGMA] = meshgrid(-10:dx:10, 1:dsig:5);
Z = exp(-(X-mu).^2./(2*SIGMA.^2))./sqrt(2*pi*SIGMA.^2);
waterfall(X,SIGMA,Z)
xlabel('x')
ylabel('sigma')
zlabel('f(x)')

The code that I have tried to write in Python so far is:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

dsig = 0.25
dx = 0.5
mu = 0

X = np.linspace(-10,dx,10)
SIGMA = np.linspace(1,dsig,5)

X, SIGMA = np.meshgrid(X, SIGMA)
Z = 1/(np.sqrt(2*np.pi*SIGMA*SIGMA))*np.exp(-(x-mu)**2/(2*SIGMA*SIGMA))

and this code keeps giving me an error.

Could please someone help me out with drawing this 3d plot in Python?

question from:https://stackoverflow.com/questions/65873873/illustrating-normal-distribution-using-numpy-matploblib-3d-from-matlab-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import math
import scipy.stats as stats

mu = 0
variance = 1
sigma = math.sqrt(variance)

x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
y = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = stats.norm.pdf(r, mu, sigma)

fig = plt.figure()
ax = fig.gca(projection='3d') # get current axis

surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

ax.set_zlim(0, 0.3)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

plt.show()

normal distribution


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...