Mastering Contour Plots with Seaborn

Contour plots, also known as density plots, are a graphical method to visualize the 3-D surface by plotting constant Z slices called contours in a 2-D format. Seaborn, a Python data visualization library based on Matplotlib, provides a convenient way to create contour plots using the kdeplot() function. This article will guide you through the process of creating and customizing contour plots using Seaborn.

Table of Content

  • Introduction to Contour Plots
  • Creating a Simple Contour Plot
  • Customizing Contour Plots Using Seaborn
    • 1. Change Color Map (cmap):
    • 2. Adjusting the Levels
    • 3. Setting the Threshold
    • 4. Removing Fill for Line-Only Plots
    • 5. Modifying Line Width (linewidths)
    • 6. Adding Gridlines

Introduction to Contour Plots

A contour plot is used to represent three-dimensional data in two dimensions using contours or color-coded regions. The contours represent lines of constant values, which can help in understanding the relationship between two variables and how they change over a range of values. Importance of Contour Plots:

  • Visualization of complex data: Enables the two-dimensional visualization of three-dimensional data. 
  • Finding Patterns: Assists in discovering trends and patterns within the data.
  • Comparison of Various Datasets: Makes it possible to compare multiple data sets using the same axes.
  • Simplified Representation: Compared to a 3D plot, this data representation is more understandable and straightforward.
  • Optimization: A technique used to visualize the objective function and find the best values in optimization issues.
  • Topographical Maps: Creates topographical maps that display the geography and elevation of a region.
  • Environmental Monitoring: Indicates how various environmental elements, such as temperature fluctuations, pollution levels, and soil composition, are distributed.
  • Medical imaging: Slices of three-dimensional entities, such as organs or tumors, are shown in medical imaging.

Creating a Simple Contour Plot

The kdeplot() function in Seaborn is used to create contour plots. You need to provide two numerical variables as input, one for each axis. The function will calculate the kernel density estimate and represent it as a contour plot.

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)

# Create a contour plot
plt.figure(figsize=(6, 6))
sns.kdeplot(x=x, y=y, fill=True, cmap="viridis", thresh=0, levels=100)
plt.title('Contour Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Basic Contour plot

Customizing Contour Plots Using Seaborn

1. Change Color Map (cmap):

Seaborn allows wide range of colors for contour maps such as ‘viridis’, ‘plasma’, ‘inferno’, ‘magma’ ,’cividis’ etc.

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)

# Create a contour plot
plt.figure(figsize=(6, 6))
sns.kdeplot(x=x, y=y, fill=True, cmap="plasma", thresh=0, levels=100)
plt.title('Contour Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Contour Plot with Plasma Color Map

2. Adjusting the Levels

To adjust the detailing of the map, we can change the number of levels in the map.

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)

# Create a contour plot
plt.figure(figsize=(6, 6))
sns.kdeplot(x=x, y=y, fill=True, cmap="viridis", thresh=0, levels=20)
plt.title('Contour Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Contour Plot with 20 Levels

3. Setting the Threshold

The threshold parameter determines the level below which the plot will not show contours.

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)

# Create a contour plot
plt.figure(figsize=(6, 6))
sns.kdeplot(x=x, y=y, fill=True, cmap="viridis", thresh=0.1, levels=100)
plt.title('Contour Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Contour Plot with Threshold of 0.1

4. Removing Fill for Line-Only Plots

Setting fill to False will create a contour plot without filled areas.

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)

# Create a contour plot
plt.figure(figsize=(6, 6))
sns.kdeplot(x=x, y=y, fill=False, cmap="viridis", thresh=0, levels=100)
plt.title('Contour Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Unfilled Contour Plot

5. Modifying Line Width (linewidths)

Change the width of contour lines to emphasize or de-emphasize them.

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)

# Create a contour plot
plt.figure(figsize=(6, 6))
sns.kdeplot(x=x, y=y, fill=False, cmap="viridis", levels=10, linewidths=2)
plt.title('Contour Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Contour Plot with Thicker Lines

6. Adding Gridlines

Python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.figure(figsize=(6, 6))

# Creating the contour plot
contour = sns.kdeplot(x=x, y=y, fill=True, cmap="coolwarm", thresh=0, levels=100)
plt.grid(True, which='both', linestyle='--', linewidth=0.5)
plt.show()

Output:

Adding Gridlines in Contour Plot

Conclusion

Contour plots are a powerful tool for visualizing the relationship between two variables and understanding the distribution of data. Seaborn’s kdeplot() function makes it easy to create and customize these plots. By adjusting parameters such as cmapbw_adjust, and adding gridlines or colorbars, you can create informative and visually appealing contour plots.