Ana Cunha
Ana Cunha

Reputation: 5

How to plot a curve for a function in a 3D graphic - Python

I have this function:

z = 0.000855995633558468*x**2 + 0.0102702516120239*x + 0.00451027901725375*y**2 - 2.23785431578513*y + 251.029058292935

I also have lists (X, Y, Z) of the coordinates of the points from this function. Then I made this code to do a plot, of that coordinates:

fig = plt.figure()
ax = fig.gca(projection='3d')
plt.plot(X, Y, Z)

plt.show() 

enter image description here

As you can see, with this code, I join the points by segments. How can I plot the curve that passes through those points?

Upvotes: 0

Views: 3836

Answers (1)

Carlo
Carlo

Reputation: 185

In short, Python does not know how all xyz points need to be connected to each other to create a surface, so it just plots lines between them.

If you want to plot a surface whose z-coordinates are a function of its x and y coordinates you need to create a grid of all the possible combinations of xy coordinates and get the resulting z-grid. Then you can plot the grids.

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

def z_func(x, y):
    z = 0.000855995633558468 * x ** 2 + 0.0102702516120239 * x + \
        0.00451027901725375 * y ** 2 - 2.23785431578513 * y + \
        251.029058292935
    return z

# Creates a 1D array of all possible x and y coordinates
x_coords = np.linspace(-30, 30, 100)
y_coords = np.linspace(180, 220, 100)

# Creates 2D array with all possible combinations of x and y coordinates,
# so x_grid.shape = (100, 100) and y_grid.shape = (100, 100)
[x_grid, y_grid] = np.meshgrid(x_coords, y_coords)

# Evaluates z at all grid points
z_grid = z_func(x_grid, y_grid)

# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_grid,y_grid,z_grid)
plt.show()

enter image description here

Upvotes: 1

Related Questions