Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display a 3D plot in Python?

I have the following code segment, but when I run it I only get a blank white screen and the plot is not displayed. I’m using Python 3.10.9. Any ideas about the issue?:

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

def np_bivariate_normal_pdf(domain, mean, variance):
    X = np.arange(-domain+mean, domain+mean, variance)
    Y = np.arange(-domain+mean, domain+mean, variance)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = ((1. / np.sqrt(2 * np.pi)) * np.exp(-.5*R**2))
    return X+mean, Y+mean, Z

def plt_plot_bivariate_normal_pdf(x, y, z):
    fig = plt.figure(figsize=(12, 6))
    ax = Axes3D(fig)
    ax.plot_surface(x, y, z,
                    cmap=cm.coolwarm,
                    linewidth=0,
                    antialiased=True)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.show()

def main():
    plt_plot_bivariate_normal_pdf(*np_bivariate_normal_pdf(4, 0, .25))

if __name__ == '__main__':
    main()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ax = Axes3D(fig) was how to create 3D axes in Matplotlib prior to version 1.0.0. Since then, use fig.add_subplot(111, projection='3d'). See here.

Full code:

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

def np_bivariate_normal_pdf(domain, mean, variance):
    X = np.arange(-domain+mean, domain+mean, variance)
    Y = np.arange(-domain+mean, domain+mean, variance)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = ((1. / np.sqrt(2 * np.pi)) * np.exp(-.5*R**2))
    return X+mean, Y+mean, Z

def plt_plot_bivariate_normal_pdf(x, y, z):
    fig = plt.figure(figsize=(12, 6))
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x, y, z,
                    cmap=cm.coolwarm,
                    linewidth=0,
                    antialiased=True)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.show()

def main():
    plt_plot_bivariate_normal_pdf(*np_bivariate_normal_pdf(4, 0, .25))

if __name__ == '__main__':
    main()

gives

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading