Python

Plotly.Graph_objects.surface

“In this article, we will explore how we can use the surface class in the Plotly graph_objects module to create a surface plot.”

Let’s dive in.

Syntax and Parameters

The surface class provides a relatively simple syntax, as shown below:

plotly.graph_objects.Surface(arg=None, hoverinfo=None, x=None, y=None, z=None,

**kwargs)

The parameters are discussed below:

  1. x – defines the values for the x coordinates.
  2. y – sets the values for the y coordinates.
  3. z – represents the values used for the z coordinates.

Basic Surface Plot

Let us start with the basics and discover how we can create a simple surface plot using graph_objects.

Consider the sample code provided below:

import plotly.graph_objects as go
import numpy as np
x = [1,2,3,4,5]
y = [1,2,3,4,5]
z = np.ones(25).reshape(5,5)

fig = go.Figure(data=go.Surface(
    x=x,
    y=y,
    z=z
))
fig.show()

The code sample above will create a flat surface, as shown in the output figure:

Topographical 3D Surface Plot

We can also use a dataset to create a surface plot. For example, the code below uses the Plotly elevation dataset to create a topographical surface plot.

import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')
fig = go.Figure(data=go.Surface(
    z=df.values
))
fig.show()

Resulting output:

Adding Contours

To add contour data, we can use the update_traces function as illustrated below:

import plotly.graph_objects as go

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')
fig = go.Figure(data=go.Surface(
    z=df.values
))
fig.update_traces(contours_z=dict(
    show=True,
    usecolormap=True,
    project_z=True
))
fig.show()

The code above will add the contour data along the z-axis, as shown in the figure below:

End

This article covers the fundamentals of creating surface plots using the Plotly graph_objects module. Explore the docs for more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list