Lesson
Contour plots
Learn Contour 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 Contour plots in the Advanced Charts with Plotly chapter of the course Data Science in Action: Interactive Visualization with Plotly and Pandas. In this lesson, you will learn about contour plots, how to create them using Plotly, and various customization options to make your visualizations more informative and appealing. Contour plots are useful for visualizing three-dimensional data in two dimensions, representing a relationship between three continuous variables, and identifying regions with similar values.
Basic Contour Plot
In this code example, we will create a basic contour plot using plotly and built-in dataset from pandas.
First, let's create a pandas dataframe using the built-in dataset iris:
import pandas as pd
import plotly.express as px
df = px.data.iris()
print(df.head())
Now, let's create a basic contour plot using the dataframe we just created:
import plotly.graph_objects as go
# Create a contour plot
fig = go.Figure(go.Contour(
x=df['sepal_width'],
y=df['sepal_length'],
z=df['petal_length'],
colorscale='Viridis',
showscale=False
))
# Set plot title and axis labels
fig.update_layout(
title="Basic Contour Plot",
xaxis_title="Sepal Width",
yaxis_title="Sepal Length"
)
fig.show()
Customizing Contour Colors
In this code example, we will demonstrate how to create a customized contour plot using Plotly and Pandas with built-in datasets. We will break the code into two blocks: one for constructing the Pandas DataFrame and another for creating the Plotly chart.
Code Block 1: Constructing the Pandas DataFrame
First, let's create the DataFrame using the built-in Iris dataset from the plotly.data module. We will then group the data by species and calculate the mean petal width and petal length for each species.
import plotly.data as data
import pandas as pd
# Load the Iris dataset
iris = data.iris()
# Group the dataset by species and calculate the mean petal width and petal length
df = iris.groupby('species').agg({
'petal_width': 'mean',
'petal_length': 'mean'
}).reset_index()
print(df)
Code Block 2: Creating the Customized Contour Plot
Now, we will create a contour plot with customized colors using Plotly. We will set the color scale to "Viridis" and adjust the number of contour levels.
import plotly.graph_objects as go
# Create the contour plot
fig = go.Figure()
fig.add_trace(go.Contour(
z=df[['petal_width', 'petal_length']].values,
x=df['petal_width'],
y=df['petal_length'],
colorscale='Viridis',
contours=dict(start=0, end=2.5, size=0.1),
line=dict(width=0.5)
))
fig.update_layout(
title='Customized Contour Plot',
xaxis_title='Petal Width',
yaxis_title='Petal Length'
)
fig.show()
Adding histogram
In this code example, we will learn how to create a contour plot with histogram.
First, let's import the necessary libraries and load the built-in dataset.
import plotly.express as px
import pandas as pd
# Load built-in dataset
df = px.data.iris()
# Print the first 5 rows of the dataset
print(df.head())
Now, we will create a contour plot using the dataset and add a histogram to it.
fig = px.density_contour(df, x="sepal_width", y="sepal_length", facet_col="species",
labels={"species": "Species", "sepal_width": "Sepal Width (cm)", "sepal_length": "Sepal Length (cm)"},
marginal_x="histogram", marginal_y="histogram")
# Show the plot
fig.show()
Customizing Contour Levels
In this code example, we will demonstrate how to customize contour levels using Plotly and the built-in dataset from Plotly Express.
Step 1: Import libraries and load the data
First, let's import the necessary libraries and load the built-in dataset from Plotly Express.
import plotly.express as px
import pyodide.http
# load volcano dataset
df = pd.read_csv(pyodide.http.open_url('https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv'))
df
Step 2: Create a contour plot with customized contour levels
Now, we will create a contour plot with customized contour levels using the data from the previous step.
import plotly.graph_objects as go
# Create a contour plot with custom contour levels
fig = go.Figure(go.Contour(
z=df.values,
contours=dict(
start=0,
end=150,
size=10,
coloring='lines',
showlabels=True
)
))
fig.show()
In this example, we specified the start, end, and size of the contour lines, as well as their coloring and the display of labels. You can further customize the appearance of the contour plot by exploring additional options in the contours dictionary.
Multiple Contour Plots
In this code example, we will create multiple contour plots using Plotly and Pandas built-in datasets. We will use the iris dataset for this example.
First, let's create the Pandas dataframe using the iris dataset and display its contents.
import pandas as pd
import plotly.express as px
# Load iris dataset
df = px.data.iris()
# Display dataframe contents
print(df.head())
Now that we have our data, let's create multiple contour plots for sepal width, sepal length, petal width, and petal length.
import plotly.graph_objects as go
# Create contour plots
fig = go.Figure()
fig.add_trace(go.Contour(x=df['sepal_width'], y=df['sepal_length'],
z=df['species_id'], name='Sepal'))
fig.add_trace(go.Contour(x=df['petal_width'], y=df['petal_length'],
z=df['species_id'], name='Petal'))
# Update layout
fig.update_layout(title='Multiple Contour Plots',
xaxis_title='Width',
yaxis_title='Length')
# Display the figure
fig.show()
This code example will generate two contour plots for iris dataset features: sepal width and length, and petal width and length.
Exercises
1. Creating a Contour Plot with the Iris Dataset
Instruction
Create a contour plot using the iris dataset to visualize the relationship between sepal width, sepal length, and petal width. Plot different species in different facets.
My Solution
# Your solution goes here
Hint
- Use facet_col='species' to create multi-facets plots.
Solution
# Create a contour plot
import plotly.express as px
# Load the iris dataset
data = px.data.iris()
# Create a contour plot with a color scale
fig = px.density_contour(data, x='sepal_width', y='sepal_length', facet_col='species')
# Show the plot
fig.show()