Lesson

Surface plots

Learn Surface plots in SQLPad's Data Science in Action: Interactive Visualization with Plotly and Pandas course with practical examples and guided lessons.

Welcome to the lesson on Surface Plots in the course Data Science in Action: Interactive Visualization with Plotly and Pandas. In this lesson, we will dive deep into creating and customizing surface plots using Plotly. Surface plots are three-dimensional plots that display the relationship between three continuous variables. They are particularly useful in visualizing complex functions, understanding the impact of multiple factors on a response variable, and identifying trends or patterns within data. With Plotly, you can create interactive and visually appealing surface plots with ease.

Creating a Basic Surface Plot

In this code example, we will create a basic surface plot using Plotly's built-in dataset and Pandas.

First, we will import the required libraries and prepare the sample dataset.

import plotly.graph_objects as go
import pandas as pd
import pyodide

# Load the volcano dataset
data = pd.read_csv(pyodide.http.open_url('https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/volcano.csv'))

data.head()

Now, we will create the surface plot using the prepared dataset.

# Create a surface plot
fig = go.Figure(data=[go.Surface(z=data.values)])

# Show the plot
fig.show()

Customizing Surface Plot Colors

In this code example, we will customize the colors of a surface plot using Plotly. We will use the built-in dataset volcano from the Plotly library.

First, let's import the necessary libraries and load the volcano dataset into a Pandas DataFrame. We will then print the first 5 rows of the data using df.head().

import plotly.express as px
import pandas as pd
import numpy as np

# Load the volcano dataset
data = np.array(px.data.volcano())

# Create a pandas dataframe from the data
df = pd.DataFrame(data)

# Print the first 5 rows of the dataframe
print(df.head())

Now, let's create a surface plot using Plotly and customize its colors. We will end the code block with fig.show() to display the chart.

import plotly.graph_objects as go

# Create a surface plot
fig = go.Figure(data=[go.Surface(z=df.values)])

# Customize the colors of the surface plot
fig.update_traces(contours=dict(z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project=dict(z=True))))

# Set the title and axis labels
fig.update_layout(title="Customized Surface Plot Colors", scene=dict(xaxis_title="X-Axis", yaxis_title="Y-Axis", zaxis_title="Z-Axis"))

# Show the plot
fig.show()

Adding a Color Scale

In this code example, we will create a surface plot with a color scale using the built-in volcano dataset from Plotly. We will first construct the pandas dataframe and then create the Plotly chart.

Code Block 1: Construct the pandas dataframe

import plotly.express as px
import pandas as pd

# Load the built-in volcano dataset
df = px.data.volcano()

# Print the first 5 rows of the dataframe
print(df.head())

Code Block 2: Construct the surface plot with a color scale

import plotly.graph_objects as go

# Create a surface plot using the volcano dataset
fig = go.Figure(data=[go.Surface(z=df.values)])

# Update the color scale
fig.update_traces(contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))

# Update the layout
fig.update_layout(title='Volcano Surface Plot with Color Scale', autosize=False,
                  width=800, height=800, scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'))

# Show the plot
fig.show()

Adjusting Opacity and Lighting

In this example, we will be adjusting the opacity and lighting of a surface plot using Plotly. We will use the volcano dataset from Plotly Express to create the surface plot.

First, let's import the necessary libraries and load the volcano dataset into a Pandas DataFrame:

import plotly.express as px
import pandas as pd

data = px.data.volcano()
df = pd.DataFrame(data)

print(df.head())

Next, let's create the surface plot and adjust the opacity and lighting:

import plotly.graph_objects as go

fig = go.Figure(go.Surface(z=df.values, opacity=0.8))

fig.update_traces(contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))

fig.update_layout(scene=dict(zaxis=dict(nticks=4), aspectratio=dict(x=1, y=1, z=0.8)),
                  scene_camera_eye=dict(x=-1.5, y=1.5, z=0.8),
                  margin=dict(r=20, b=10, l=10, t=10))

fig.show()

Contour Lines on Surface Plots

In this code example, we'll create a surface plot with contour lines using Plotly and a built-in dataset from Plotly. We will break down the code into two parts: preparing the data and creating the chart.

Preparing the Data

First, let's prepare the data by loading the built-in Plotly dataset "z_data" and creating a pandas dataframe.

import plotly.express as px
import pandas as pd

# Load built-in dataset from Plotly
z_data = px.data.election()

# Create a pandas dataframe
df = pd.DataFrame(z_data)

# Preview the dataframe
print(df.head())

Creating the Contour Lines on Surface Plot

Now let's create a surface plot with contour lines using the prepared data. We will customize the plot appearance by adding title, axis labels, and adjusting the contour lines.

import plotly.graph_objects as go

# Create a surface plot with contour lines
fig = go.Figure(data=[go.Surface(z=df.values, contours=dict(z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project=dict(z=True))))])

# Customize plot appearance
fig.update_layout(title="Contour Lines on Surface Plot", autosize=False, width=800, height=800, scene=dict(xaxis_title="X-Axis", yaxis_title="Y-Axis", zaxis_title="Z-Axis"))

# Show the plot
fig.show()

Try running these code blocks one by one in the online playground provided, and explore the contour lines on the surface plot!

Subplots with Surface Plots

In this code example, we will create subplots with surface plots using the Plotly library. Let's start by importing the necessary libraries and creating the data.

Code Block 1: Creating the Data

import plotly.express as px
import pandas as pd
import numpy as np

# Creating the data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x_grid, y_grid = np.meshgrid(x, y)
z1 = np.sin(np.sqrt(x_grid**2 + y_grid**2))
z2 = np.cos(np.sqrt(x_grid**2 + y_grid**2))

# Creating the dataframes
df1 = pd.DataFrame({'x': x_grid.ravel(), 'y': y_grid.ravel(), 'z': z1.ravel()})
df2 = pd.DataFrame({'x': x_grid.ravel(), 'y': y_grid.ravel(), 'z': z2.ravel()})

print(df1.head())
print(df2.head())

Now that we have our data, let's create the subplots with surface plots.

Code Block 2: Creating the Subplots with Surface Plots

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Creating the subplots
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'surface'}, {'type': 'surface'}]])

# Adding the surface plots
fig.add_trace(go.Surface(x=df1['x'], y=df1['y'], z=df1['z'], name='z1'), row=1, col=1)
fig.add_trace(go.Surface(x=df2['x'], y=df2['y'], z=df2['z'], name='z2'), row=1, col=2)

# Updating the layout
fig.update_layout(title='Subplots with Surface Plots', scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z1'),
                  scene2=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z2'))

fig.show()

Animating Surface Plots

In this code example, we will create an animated surface plot using the built-in dataset volcano from Plotly. We will break the code down into two blocks: one for preparing the data and another for constructing the chart.

Block 1: Preparing the data

import plotly.express as px
import pandas as pd

df = px.data.volcano()
print(df)

Block 2: Constructing the chart

import plotly.graph_objects as go

fig = go.Figure()

for i, z_data in enumerate(df.columns[1:]):
    fig.add_trace(go.Surface(z=df[z_data].values.reshape((32, 32)), 
                             x=df['X'],
                             y=df['Y'], 
                             name=z_data,
                             visible=(i==0)))

steps = []
for i, z_data in enumerate(df.columns[1:]):
    step = dict(method='restyle', args=['visible', [False] * len(df.columns[1:])],
                label=z_data)
    step['args'][1][i] = True
    steps.append(step)

sliders = [dict(active=0, pad={"t": 20}, steps=steps)]

fig.update_layout(scene=dict(zaxis_title="Height", 
                             xaxis_title="X-axis",
                             yaxis_title="Y-axis"),
                  sliders=sliders,
                  title="Animating Surface Plots")

fig.show()

In the first block, we import the necessary libraries and load the volcano dataset. In the second block, we create a figure using go.Figure() and add traces for each column in the dataset. We then create and add sliders for controlling the animation and update the layout of the figure. Finally, we display the animated surface plot using fig.show().

Exercises

1. Creating a Surface Plot with Custom Color Scale and Opacity

Instruction

  1. Create a meshgrid of x, y, and z values using numpy.
  2. Create a surface plot using the go.Surface function with the custom color scale 'Viridis' and opacity 0.8.
  3. Set the title and axis labels using the update_layout function.
  4. Display the plot using fig.show().

My Solution

# Your solution goes here

Hint

Use the colorscale and opacity parameters in the go.Surface function to customize the appearance of the surface plot.

Solution

x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x_grid, y_grid = np.meshgrid(x, y)
z_grid = np.sin(np.sqrt(x_grid**2 + y_grid**2))

fig = go.Figure(data=[go.Surface(x=x_grid, y=y_grid, z=z_grid, colorscale='Viridis', opacity=0.8)])

fig.update_layout(title='Customized Surface Plot', scene=dict(xaxis_title='x-axis', yaxis_title='y-axis', zaxis_title='z-axis'))

fig.show()