Contour Plot using Seaborn

logo of a chart:2dDensity

This post explains how to draw a contour plot (density plot) using kdeplot() function of seaborn library.
In this post, you will learn how to draw a 2D density plot and how to customize it.

Libraries

First, we need to import a few libraries:

import matplotlib.pyplot as plt
import seaborn as sns

Dataset

The dataset that we will use is the iris dataset that we can load using seaborn.

df = sns.load_dataset('iris')

Most simple density plot

The following code produces 3 contour plots using seaborn python library. You have to provide 2 numerical variables as input (one for each axis). The function will calculate the kernel density estimate and represent it as a contour plot or density plot.

The aguments of the function kdeplot() are:

  • x, y : Variables that specify positions on the x and y axes.
  • shade : Controls the presence of a shade.
  • cmap : Colormap.
  • bw_adjust : Bandwidth, smoothing parameter.
  • thresh : number in [0, 1], Lowest iso-proportion level at which to draw a contour line.

Here is how we can create the default 2D density plot:

sns.set_style("white")
sns.kdeplot(x=df.sepal_width, y=df.sepal_length)
plt.show()

Change colors

In order to make the chart more readable, we can add colormap to the plot:

sns.set_style("white")
sns.kdeplot(x=df.sepal_width, y=df.sepal_length, cmap="Reds", fill=True)
plt.show()

Change smoothing parameter

The bw_adjust argument controls the bandwidth of the kernel density estimate. The higher the value, the smoother the plot will be. Here is an example with a bw_adjust value of 0.5:

sns.set_style("white")
sns.kdeplot(x=df.sepal_width, y=df.sepal_length,
            cmap="Blues", fill=True, bw_adjust=0.5)
plt.show()

Going further

This post explains how to create a 2D density plot with seaborn.

You might be interested in how to create a hexbin plot and how to create a 2D histogram.

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!