How to create a 3D surface plot with Plotly Graph Objects

Plotly Graph Objects is a Python library that provides a flexible and powerful way to create interactive data visualizations. It is part of the larger Plotly ecosystem, which includes Plotly Express and Plotly.py. Plotly Graph Objects allows us to create and customize various charts, plots, and graphs with full control over the visual aspects and interactivity.

Features of the 3D surface plot in Plotly Graph Objects

The following are some key features of 3D surface plots using Plotly Graph Objects:

  • Data input: We can create 3D surface plots by providing data as a 2D grid of values. Our data can be a NumPy array, a pandas DataFrame, or a list of lists.

  • Surface plot: We typically use the go to create a 3D surface plot. Surface trace type in Plotly.

  • x, y, and z axes: We can specify the xx, yy, and zz axes for our surface plot. These are usually defined by the data we provide. For example, if our data is a grid, the xxand yyaxes correspond to the row and column indices, while the zzaxis represents the values at each grid point.

  • Color and color scale: We can map the values of the zzaxis to colors using a specified color scale. Plotly provides various built-in color scales, and we can also create custom color scales. The color scale attribute allows us to control the color mapping.

  • Opacity: We can control the opacity of the surface plot using the opacity attribute. Depending on our visualization needs, this can make the plot more or less transparent.

  • Contours: We can add contour lines to our surface plot using the contours attribute. This allows us to visualize the 2D projections of the surface plot on the xyxy, xzxz, or yzyz planes.

  • Lighting and shading: Plotly allows us to customize the lighting and shading of the 3D surface plot. We can adjust parameters like lighting.ambient, lighting.diffuse, and lighting.specular, to control how the plot is illuminated.

  • Color bar: We can include a color bar alongside our 3D surface plot to indicate the correspondence between colors and data values. The color bar attribute provides control over its appearance and placement.

  • Titles and labels: We can add titles and labels to the plot and axes to provide context and clarity to our visualization. We use the title, xaxis.title, yaxis.title, and zaxis.title attributes to set titles.

  • Scene: In a 3D plot, we can define the layout and appearance of the scene. This includes setting the camera position, aspect ratio, and more through the scene attribute.

  • Annotations: We can add annotations to our 3D surface plot to highlight specific data points or regions. Annotations can include text labels, lines, or shapes.

  • Interactive features: Plotly 3D surface plots are interactive by default. Users can pan, zoom, and rotate the plot to explore it from different angles.

  • Export options: We can save our 3D surface plot as an image (e.g., PNG or JPEG) or as an interactive HTML file.

Syntax

The 3D surface plot syntax typically follows this structure:

import plotly.graph_objects as go
surface_trace = go.Surface(
x=x, # x-axis data
y=y, # y-axis data
z=z, # z-axis data
colorscale='Viridis', # Color scale
contours=dict(z=dict(show=True, highlightwidth=0.1)), # Contour lines (optional)
)
Syntax of the 3D surface plot

Parameters

The following are the key parameters for creating a 3D surface plot using Plotly Graph Objects:

  • x: The xx-axis data points. This can be a list or array of values representing the xx-coordinates of our data grid.

  • y: The yy-axis data points. Similarly, this is a list or array representing the yy-coordinates of our data grid.

  • z: The zz-axis data points. This is a 2D list or array representing the values at each grid point in the xx-yy plane. It corresponds to the height or value of the surface at each (x, y) coordinate.

  • colorscale: Specifies the color scale used to map the zz-values to colors. We can choose from various predefined color scales like Viridis, Jet, Rainbow, or create custom color scales.

  • contours: An optional dictionary that allows us to configure contour lines on the surface plot. We can control the display of contour lines using attributes like show, coloring, and highlightwidth.

  • opacity: Sets the opacity of the surface. It's a value between 0 (completely transparent) and 1 (completely opaque).

  • cmin and cmax: These parameters allow us to specify the minimum and maximum values for the color scale. Values outside this range will be mapped to the endpoints of the color scale.

  • lighting: A dictionary that controls the lighting of the surface plot. We can adjust parameters like ambient, diffuse, and specular to customize how light interacts with the plot's surface.

  • colorbar: Allows us to customize the colorbar associated with the surface plot. We can set attributes like title, titleside, and tickvals.

  • hoverinfo: Specifies what information is displayed when hovering over data points on the plot. We can include information about X, Y, Z values, or customize it further.

  • scene: A dictionary that configures the layout and appearance of the 3D scene. We can set attributes like xaxis_title, yaxis_title, zaxis_title, and camera (for adjusting the view angle).

  • showscale: Determines whether or not to display a color scale alongside the plot.

  • name: The name of the trace, which can be useful when working with multiple traces in the same figure.

  • reversescale: Specifies whether to reverse the color scale.

  • surfacecolor: Allows us to set a constant color for the entire surface.

  • coloraxis: A dictionary to control how color scaling is applied. We can set attributes like colorbar, colorbar_title, and colorscale.

Return type

When we create a visualization like a 3D surface plot using the go.Surface trace and the go.Figure constructor, we are essentially creating a figure object that represents our plot. The figure object contains all the necessary information about our plot, including the data, traces, layout, and any additional settings or customizations we've applied.

Implementation

In the following playground, we create a 3D surface plot using a sample dataset called iris provided by Plotly Express. Used attributes (sepal_width, sepal_length and petal_width) defined as follows:

  • sepal_width: This attribute represents the width of the sepals of iris flowers. Sepals are the leaf-like structures that protect the flower's bud before it blooms. Sepal width is typically measured in centimeters (cm).

  • sepal_length: This attribute represents the length of the sepals of iris flowers. Like sepal width, it is also measured in centimeters (cm). Sepal length provides information about the size and shape of the sepals.

  • petal_width: This attribute represents the width of the petals of iris flowers. Petals are the colorful, leaf-like structures inside a flower that are involved in attracting pollinators. Petal width is measured in centimeters (cm).

cd /usercode && python3 main.py
python3 -m http.server 5000 > /dev/null 2>&1 &
Visualizing petal_width with a 3D surface plot in relation to sepal_width and sepal_length

Explanation

The code above is explained in detail below:

  • Lines 1–3: Import the necessary modules: plotly.graph_objects for creating custom plots, plotly.express for simplified plotting, and pandas for data manipulation.

  • Line 6: Load the Iris dataset using Plotly Express's built-in sample dataset.

  • Line 9: Print the first five rows of the loaded dataset using the head() method to inspect the data.

  • Lines 12–16: A 3D surface plot trace is created using Plotly's graph_objects. The z-axis (vertical) is assigned the petal_width column from the dataset, the x-axis is assigned sepal_width, and the y-axis is assigned sepal_length.

  • Line 19: This line creates a new figure using Plotly's graph_objects and adds the 3D surface plot trace surface_trace to it. A figure is a container for plots.

  • Line 22: Update the layout of the figure by setting its title.

  • Line 25: Display the finalized 3d surface plot figure using the show() method.

Conclusion

3D surface plots in Plotly Graph Objects offer a powerful means of visualizing complex, multidimensional data. This capability is particularly valuable for understanding relationships within three dimensions of data points. Plotly's flexible library allows for precise customization, from controlling color scales and contour lines to adjusting lighting and layout. As a result, it empowers data analysts and scientists to create interactive and informative 3D surface plots that reveal insights, patterns, and trends in their data, making it a valuable tool in the field of data visualization and analysis.


Unlock your potential: Plotly Graphing and Visualization series, all in one place!

To deepen your understanding of data visualization using Plotly, explore our comprehensive Answer series below:

Plotly express: quick and intuitive visualization

Plotly Graph Objects: Customization and advanced features

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved