3D surface plots using Plotly in Python
A 3D surface plot represents the relationship between two independent variables and a dependent variable.
In this Answer, we'll look at implementing 3D surface plots using Plotly.
Code sample
import plotly.graph_objects as go
import numpy as np
independentVariable1 = np.linspace(-5, 5, 100)
independentVariable2 = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(independentVariable1, independentVariable2)
dependentVariable = np.sin(np.sqrt(X**2 + Y**2))
fig = go.Figure(data=[go.Surface(x=independentVariable1, y=independentVariable2, z=dependentVariable, colorscale='Blues')])
fig.update_layout(
title='3D Surface Plot',
scene=dict(
xaxis_title='Independent Variable 1',
yaxis_title='Independent Variable 2',
zaxis_title='Dependent Variable'
)
)
fig.show()
fig.write_html("output.html", auto_open=True)Code explanation
Lines 1–2: Let's import the necessary modules for our code, including
plotly.graph_objectsasgofor interactive plotting, andnumpyasnp.Lines 4–5: We define the independent variables,
independentVariable1andindependentVariable2(commonly referred to as x and y), by creating two arrays usingnp.linspace(). This generates 100 equal points between -5 and 5 for each.Line 7: We create a grid of coordinates
XandYusingnp.meshgrid()withindependentVariable1andindependentVariable2.Line 9: We then calculate the dependent variable,
dependentVariable, by applying the sine function to the square root of the sum of squares ofXandY. This generates the Z-values for the 3D surface plot.Line 11: We create a
Figureobject usinggo.Figure()and then add aSurfaceto it. Thex,y, andzarguments are set toindependentVariable1,independentVariable2, anddependentVariable, respectively. For some aesthetic colors, we can specifycolorscale. Here, it's set to "Blues".Lines 13–20: We update the layout of the figure using
fig.update_layout(), including thetitleand thescene.Line 22: Finally, we display the plot using
fig.show().
Output
Interactive representation
We can interact with the rendered plot in various ways, as depicted in the video below. You can experiment with the plot yourself by clicking the "Run" button in the code.
End notes
The above code depicts the efficiency of Plotly in creating high-resolution and interactive plots such as 3D surface plots. One of Plotly's standout features is its support for 3D surface plots. These plots are really useful for visualizing data in three dimensions, where the x and y-axes represent two variables, and the z-axis represents a third variable. By employing the plot_surface() function, we were able to generate captivating 3D visualizations with just a few lines of code!
Free Resources