5

I have obtained the means and sigmas of 3d Gaussian distribution, then I want to plot the 3d distribution with python code, and obtain the distribution figure.

1
  • What code have you tried so far? Commented Nov 16, 2016 at 2:06

2 Answers 2

8

This is based on documentation of mpl_toolkits and an answer on SO based on scipy multinormal pdf:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

import numpy as np
from scipy.stats import multivariate_normal

x, y = np.mgrid[-1.0:1.0:30j, -1.0:1.0:30j]

# Need an (N, 2) array of (x, y) pairs.
xy = np.column_stack([x.flat, y.flat])

mu = np.array([0.0, 0.0])

sigma = np.array([.5, .5])
covariance = np.diag(sigma**2)

z = multivariate_normal.pdf(xy, mean=mu, cov=covariance)

# Reshape back to a (30, 30) grid.
z = z.reshape(x.shape)





fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')



ax.plot_surface(x,y,z)
#ax.plot_wireframe(x,y,z)

plt.show()

reference:-

  1. Generating 3D Gaussian distribution in Python

  2. https://matplotlib.org/tutorials/toolkits/mplot3d.html#sphx-glr-tutorials-toolkits-mplot3d-py

Sign up to request clarification or add additional context in comments.

1 Comment

Not to be pedantic, but doesn't "3D Gaussian Distribution" imply that the input is 3D? This and the other SO question you linked treat 2D gaussian distributions...
0

Another example without using scipi:

import numpy as np
import matplotlib.pyplot as plt

ax = plt.axes(projection="3d")

mesh_size=100
max=mesh_size**2
xyz = np.zeros((3,max))
nx, ny = (mesh_size,mesh_size)
x = np.linspace(-1, 1, nx)
y = np.linspace(-1, 1, ny)
xv, yv = np.meshgrid(x, y)
xyz[0]=xv.reshape(max,)
xyz[1]=yv.reshape(max,)
xyz[2]=np.exp(-(xyz[0]**2+xyz[1]**2))

ax.scatter(xyz[0],xyz[1],xyz[2])
ax.set_title("3D Plot")

plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.