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_objects as go for interactive plotting, and numpy as np.

  • Lines 4–5: We define the independent variables, independentVariable1 and independentVariable2 (commonly referred to as x and y), by creating two arrays using np.linspace(). This generates 100 equal points between -5 and 5 for each.

  • Line 7: We create a grid of coordinates X and Y using np.meshgrid() with independentVariable1 and independentVariable2.

  • Line 9: We then calculate the dependent variable, dependentVariable, by applying the sine function to the square root of the sum of squares of X and Y. This generates the Z-values for the 3D surface plot.

  • Line 11: We create a Figure object using go.Figure() and then add a Surface to it. The x, y, and z arguments are set to independentVariable1, independentVariable2, and dependentVariable, respectively. For some aesthetic colors, we can specify colorscale. Here, it's set to "Blues".

  • Lines 13–20: We update the layout of the figure using fig.update_layout(), including the title and the scene.

  • Line 22: Finally, we display the plot using fig.show().

Output

3D surface plot using Plotly displayed in the browser
3D surface plot using Plotly displayed in the browser

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

Copyright ©2024 Educative, Inc. All rights reserved