How to plot a one to many function on matplotlib in python

Very simple, if I plot x^2+y^2=z it makes this shape on python it will make this shape:

1

When I would like to plot it this way:

2

Below is my code, I am new so I copied it from the internet and have changed the line with the function to plot.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-4*np.pi,4*np.pi,50)
y = np.linspace(-4*np.pi,4*np.pi,50)
z = x**2+y**2
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x,y,z)
plt.show()

Also, how do I make it more high definition and smooth, this is a graph of z=sin(x)

3


Solution 1:

You need to define a 2D mathematical domain with numpy.meshgrid, then you can compute the surface on that domain:

X, Y = np.meshgrid(x, y)

Z = X**2 + Y**2

In order to increase the smoothness of the surface, you have in increase the number of point N you use to compute x and y arrays:

Complete code

import matplotlib.pyplot as plt
import numpy as np

N = 50

x = np.linspace(-4*np.pi, 4*np.pi, N)
y = np.linspace(-4*np.pi, 4*np.pi, N)

X, Y = np.meshgrid(x, y)

Z = X**2 + Y**2

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

ax.plot_surface(X, Y, Z)

plt.show()

enter image description here