Callysto.ca Banner

Open in Callysto

3D Plotting in Plotly

Plotly’s Python library is free and open source! It provides a rich environment for all kinds of graphs (line graphs, scatter plots, histograms, bubble plots, and more.)

To learn all about Plotly for use in Python, please see the documentation online at https://plotly.com/graphing-libraries/

For more 3D examples, see: https://plotly.com/python/3d-surface-plots/

Example 1

Here is a very simple example.

First step is to load in the appropriate modules for Plotly.

import plotly.graph_objs as go

Next we create an array of z values – these will be heights in the surface plot.

We keep it simple, use a 9x9 array of integers, ordered like a 3D hill.

We the use the go module to create the surface and display as a figure.

zdata = [
    [0,0,0,0,1,0,0,0,0],
    [0,0,0,1,2,1,0,0,0],
    [0,0,1,2,3,2,1,0,0],
    [0,1,2,3,4,3,2,1,0],
    [1,2,3,4,4,4,3,2,1],
    [0,1,2,3,4,3,2,1,0],
    [0,0,1,2,3,2,1,0,0],
    [0,0,0,1,2,1,0,0,0],
    [0,0,0,0,1,0,0,0,0],
  ]

fig = go.Figure(data = go.Surface(z=zdata))

fig.show()

Example 2

Here is a more mathematical example, where we plot a function of two variables, z = f(x,y). This creates a surface. For fun, we will make three surfaces at different heights.

Note the use of the meshgrid functions, to create an array out of the x and y values in the plane.

import numpy as np

# Creating the data
x = np.linspace(-3, 3, 50)
y = np.linspace(-3, 3, 50)
xGrid, yGrid = np.meshgrid(y, x)
z0 = np.exp(-xGrid ** 2 - yGrid ** 2)

z1 = z0+2
z2 = z0+4

fig = go.Figure(data = [
    go.Surface(z=z0),
    go.Surface(z=z1, showscale=False, opacity=0.7),
    go.Surface(z=z2, showscale=False, opacity=0.7)]
               )

fig.show()

Example 3

Here is a more complicated example that comes from the Plotly webpages.

import numpy as np

# Creating the data
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
xGrid, yGrid = np.meshgrid(y, x)
R = np.sqrt(xGrid ** 2 + yGrid ** 2)
z = np.sin(R)

# Creating the plot
lines = []
line_marker = dict(color='#0066FF', width=2)
for i, j, k in zip(xGrid, yGrid, z):
    lines.append(go.Scatter3d(x=i, y=j, z=k, mode='lines', line=line_marker))

layout = go.Layout(
    title='Wireframe Plot',
    scene=dict(
        xaxis=dict(
            gridcolor='rgb(255, 255, 255)',
            zerolinecolor='rgb(255, 255, 255)',
            showbackground=True,
            backgroundcolor='rgb(230, 230,230)'
        ),
        yaxis=dict(
            gridcolor='rgb(255, 255, 255)',
            zerolinecolor='rgb(255, 255, 255)',
            showbackground=True,
            backgroundcolor='rgb(230, 230,230)'
        ),
        zaxis=dict(
            gridcolor='rgb(255, 255, 255)',
            zerolinecolor='rgb(255, 255, 255)',
            showbackground=True,
            backgroundcolor='rgb(230, 230,230)'
        )
    ),
    showlegend=False,
)
fig = go.Figure(data=lines, layout=layout)
fig.show()

Callysto.ca License