Sometimes, wwe want to add surface plots in Python matplotlib.
In this article, we’ll look at how to add surface plots in Python matplotlib.
How to add surface plots in Python matplotlib?
To add surface plots in Python matplotlib, we can use the plot_surface
method.
For instance, we write
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
def fun(x, y):
return x**2 + y
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
to create the fun
function that we use to get the z-axis values.
Then we create “xand
yarrays with
np.arange(-3.0, 3.0, 0.05)`.
And we call meshgrid
with them to create the X
and Y
values we want to plot for the x and y axes.
Next, we create the zs
array with np.array
with the fun
function called on the x and y axes values that we get with ravel
.
And then we call zs.reshape
with X.shape
to create the Z
axis that we can plot.
Then we call plot_surface
with X
, Y
and Z
to plot the surface with the points.
And we call set_xlabel
, set_ylabel
, and set_zlabel
to set the axis labels.
Finally, we call show
to show the plots.
Conclusion
To add surface plots in Python matplotlib, we can use the plot_surface
method.