To visualize the relationship between three variables, we generally need a three-dimensional graph. Surface plots are two-dimensional diagrams of three-dimensional data. Surface plots show the functional relationship between independent and dependent variables.
In Python, we draw surface plots using matplotlib.
1. Import libraries
We don’t need to import the entire matplotlib module, pyplot should be enough. Make sure to import numpy for any mathematics needed for the plot.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
2. Introduce data
This usually comprises of two independent-variable arrays and a dependent variable array.
x = np.arange(0, 25, 1)
y = np.arange(0, 25, 1)
x, y = np.meshgrid(x, y)
z = x + y
3. Draw a plot
fig = plt.figure()
axes = fig.gca(projection ='3d')
axes.plot_surface(x, y, z)
plt.show()
import numpy as np # For mathematics, and making arraysimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D# Arrays x, y and z for data plot visualizationx = np.arange(0, 25, 1)y = np.arange(0, 25, 1)# meshgrid makes a retangular grid out of two 1-D arrays.x, y = np.meshgrid(x, y)z = x**2 + y**2 # x^2+y^2# surface plot for x^2 + y^2fig = plt.figure() # creates space for a figure to be drawn# Uses a 3d prjection as model is supposed to be 3Daxes = fig.gca(projection ='3d')# Plots the three dimensional data consisting of x, y and zaxes.plot_surface(x, y, z)# show command is used to visualize data plotplt.show()