Public account: You and the cabin by: Peter Editor: Peter

Hello, I’m Peter

This article focuses on how to use Plotly to draw 3D graphics.

In 3D graphics, there are usually three axes: x, y and Z. In Plotly, when setting the layout, we usually set a parameter called scene. This parameter includes x, Y, z3 axis Settings, such as axis range, name, color, etc. It also introduces different types of 3D graphics, such as 3D scatter plots and 3D planar graphs

A sneak peek

First let’s take a look at some of the 3D graphics implemented by Plotly. Do you believe they are actually the same?






Plotly serial

The full list of Plotly’s current articles is as follows:

Import library, data

Many graphs in this paper are drawn based on iris data set, so we enter database and data set first:

import pandas as pd
import numpy as np

import plotly.express as px
import plotly.graph_objects as go
Copy the code

3D Scatter: Based on PlotLY_Express

Basic 3D graphics

The simplest 3D figure, drawn using px.scatter_3D:

fig = px.scatter_3d(
  iris,
  x="sepal_length",
  y="sepal_width",
  z="petal_width",
  color="species"
)

fig.show()
Copy the code

Set scatter to different shapes and sizes;

You can also add a different Markder tag to each scatter

fig = px.scatter_3d(
  iris,
  x="sepal_length",
  y="sepal_width",
  z="petal_length",
  color="petal_width",
  symbol="species"
)

fig.show()
Copy the code

# set scatter size

fig = px.scatter_3d(
  iris,
  x="sepal_length",
  y="sepal_width",
  z="petal_width",
  color="petal_length",
  size="petal_length",
  size_max=18.# Scatter maximum
  opacity=0.7.# transparency
  symbol="species"
)
fig.update_layout(margin=dict(l=0,r=0,b=0,t=0))

fig.show()
Copy the code

3D Scatter: Based on go.scatter3DMe

Basic 3D Graphics

import plotly.graph_objects as go
import numpy as np

# Simulation data
t = np.linspace(0.10.50)
x, y, z = np.cos(t), np.sin(t), t

fig = go.Figure(data=[go.Scatter3d(
    x=x,  # Set 3 different coordinate data
    y=y, 
    z=z,
    mode='markers')])  # 'lines', 'markers', 'text

fig.show()
Copy the code

Change the color of the scatter:

import plotly.graph_objects as go
import numpy as np

N = 88
t = np.linspace(0.20, N)
x, y, z = np.cos(t), np.sin(t), t

fig = go.Figure(data=[go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    marker=dict(  # Set the tag
        size=10,
        color=z,  # color Settings
        colorscale='Viridis'.# Select color
        opacity=0.86  # transparency)))# Set the marginal range of the graph
fig.update_layout(margin=dict(l=4, r=4, b=0, t=0))
fig.show()
Copy the code

3D floor plan: Go.surface implementation

3D plan based on terrain

The data used are as follows:

import plotly.graph_objects as go

import pandas as pd

# Read the online CSV file

z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv',
                     index_col=0)  The # index_col parameter indicates that the data in the first column is used as the index
z_data.head()
Copy the code

fig = go.Figure(data=[go.Surface(z=z_data.values)])

fig.update_layout(title="3D Surface Graphics Rendering".# titles
                  autosize=False.# Scale automatically
                  width=700.# width
                  height=600,
                  margin=dict(l=65,r=50,b=65,t=90)  # distance of 4 positions
                 )

fig.show()
Copy the code

3D graphics with outline lines

# Same data as above

# 1. Mr. Canvas
fig = go.Figure(data=[go.Surface(z=z_data.values)])

fig.update_traces(contours_z=dict(  # Profile Settings
    show=True.# Enable display or not
    usecolormap=True.# color Settings
    highlightcolor="mistyrose".# highlight
    project_z=True))

fig.update_layout(
    title='3D plan with outline',
    autosize=False,
    scene_camera_eye=dict(x=1.87, y=0.88, z=-0.64),
    width=600, 
    height=500,
    margin=dict(l=65, r=50, b=65, t=90)
)

fig.show()
Copy the code

Multiple 3D graphics

Draw multiple figures on a Canvas in China:

z1 = np.array([  Numpy is an array form
    [8.83.8.89.8.81.8.87.8.9.8.87],
    [8.89.8.94.8.85.8.94.8.96.8.92],
    [8.84.8.9.8.82.8.92.8.93.8.91],
    [8.79.8.85.8.79.8.9.8.94.8.92],
    [8.79.8.88.8.81.8.9.8.95.8.92],
    [8.8.8.82.8.78.8.91.8.94.8.92],
    [8.75.8.78.8.77.8.91.8.95.8.92],
    [8.8.8.8.8.77.8.91.8.95.8.94],
    [8.74.8.81.8.76.8.93.8.98.8.99]
])

z2 = z1 + 5
z3 = z1 - 5

fig = go.Figure(data=[
    go.Surface(z=z1),
    go.Surface(z=z2, showscale=False, opacity=0.9),
    go.Surface(z=z3, showscale=False, opacity=0.9)

])

fig.show()
Copy the code

6 3D Bubble diagram: 3D Bubble

6.1 Implementation based on Plotly_Express

data = px.data.gapminder()  # GDP data set

fig = px.scatter_3d(data,  # incoming data
                    x='year'.# Select 3 coordinates
                    y='continent', 
                    z='pop', 
                    size='gdpPercap'.# Bubble size
                    color='lifeExp'.# color
                    hover_data=['country'])  # Hover data

# If the data is too large, you can use logarithms
fig.update_layout(scene_zaxis_type="log")  Take the logarithm of the z axis

fig.show()
Copy the code

6.2 Implementation based on go.scatter3D

Data section:

start, end = 800.1200  Select start and end indexes to filter data

fig = go.Figure(data=go.Scatter3d(
    x=df1['year'][start:end],  # Slice out some data by setting the value
    y=df1['continent'][start:end],
    z=df1['pop'][start:end],
    text=df1['country'][start:end], # Text display data
    mode='markers'.# Display form of bubbles: marker
    marker=dict(   
        sizemode = 'diameter'.Size: 'diameter', 'area'
        sizeref = 1500,
        size = df1['gdpPercap'][start:end],
        color = df1['lifeExp'][start:end],
        colorscale = 'Viridis',
        line_color='rgb(140, 140, 170)'
    )
))


fig.update_layout(height=800, 
                  width=800,
                  title='3D bubble Drawing ')

fig.show()
Copy the code

7 3D Isosurface Diagram

Use go.isosurface to draw

7.1 Basic 3D Equivalent

import plotly.graph_objects as go

fig= go.Figure(data=go.Isosurface(
    x=[0.0.0.0.1.1.1.1].# Set 3 coordinates
    y=[1.0.1.0.1.0.1.0],
    z=[1.1.0.0.1.1.0.0],
    
    value=[1.2.3.4.5.6.7.8].# set the value
    
    isomin=2.Color range
    isomax=7,
))

fig.show()
Copy the code

7.2 Changing the number of contour surfaces

Mgrid, a function from Numpy, is used in the following example:

  • The np.mgrid function returns multidimensional structures, such as 2D graphics, 3D graphics.
  • Compared to NP. meshGrid, it can process big data faster and can handle multiple dimensions (nP. MeshGrid can only handle two dimensions).
  • Ret = np.mgrid[dimension 1, dimension 2, dimension 3…] : returns multiple values, as multiple matrices,
  • The first return value is the distribution of the first dimension data in the final structure, the second return value is the distribution of the second dimension data in the final structure, and so on.

import plotly.graph_objects as go
import numpy as np

Use numpy's mgrid function to generate three pieces of data
X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j]

# values
values = X * X * 0.5 + Y * Y + Z * Z * 2

fig = go.Figure(data=go.Isosurface(
    x=X.flatten(),
    y=Y.flatten(),
    z=Z.flatten(),
    value=values.flatten(),
    isomin=10,
    isomax=50,
    surface_count=5, 
    colorbar_nticks=5, 
    caps=dict(x_show=False, y_show=False)
    ))

fig.show()
Copy the code

Change color and transparency

import plotly.graph_objects as go
import numpy as np

Use numpy's mgrid function to generate three pieces of data
X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j]

# values
values = X * X * 0.5 + Y * Y + Z * Z * 2

fig = go.Figure(data=go.Isosurface(
    x=X.flatten(),
    y=Y.flatten(),
    z=Z.flatten(),
    value=values.flatten(),
    opacity=0.6.# Change the opacity of the graph
    colorscale='plotly3'.# Change color
    isomin=10,
    isomax=50,
    surface_count=5, 
    colorbar_nticks=5, 
    caps=dict(x_show=False, y_show=False)
    ))

fig.show()
Copy the code

Advanced contour surface diagram

Generate 3 numpy arrays
X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j]

# the specific value
values = X * X * 0.5 + Y * Y + Z * Z * 2

fig = go.Figure(data=go.Isosurface(
    x=X.flatten(),  # 3 coordinates
    y=Y.flatten(),
    z=Z.flatten(),
    value=values.flatten(),  # data values
    isomin=5.# Range of values
    isomax=50,
    surface_fill=0.7.# Surface fill chroma
    caps=dict(x_show=False, y_show=False),
    slices_z=dict(show=True, locations=[-1, -9, -5]),
    slices_y=dict(show=True, locations=[1.8]),
    ))

fig.show()
Copy the code

X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j.0:5:20j]

values = X * X * 0.5 + Y * Y + Z * Z * 2

fig = go.Figure(data=go.Isosurface(
    x=X.flatten(),  # 3 axes and values
    y=Y.flatten(),
    z=Z.flatten(),
    value=values.flatten(),
    isomin=30.# The size of an equal surface
    isomax=50,
    surface=dict(count=3, fill=0.7, pattern='odd'),  # pattern values: 'all', 'odd', 'even'
    caps=dict(x_show=True, y_show=True),
    ))

fig.show()
Copy the code