Seaborn Syntax

Seaborn

Seaborn - Statistical Data Visualization

Introduction

Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics.

Documentation

Importing Module

Seaborn is commonly imported as sns.

import seaborn as sns

Displaying Plots

When we are ready to display the plots we call pyplot.show().

import seaborn as sns
import matplotlib.pyplot as plt
. 
. some code with seaborn to create the plot
.
plt.show()

Histograms & KDE

We can generate a histogram using seaborn.distplot() function.

sns.distplot(dataframe_obj[col_name])
plt.show()

Kernel Density Plot

In order to generate just the Kernel Density Plot (KDE) we use the sns.kdeplot() function.

sns.kdeplot(dataframe_obj[col_name], shade=True)

The shade parameter will shade the area under the graph when set to True.

Plot Appearance

Styles

We can use the seaborn.set_style() function to change the default Seaborn style sheet. Seaborn comes with a few style sheets:

  • darkgrid: Coordinate grid displayed, dark background color
  • whitegrid: Coordinate grid displayed, white background color
  • dark: Coordinate grid hidden, dark background color
  • white: Coordinate grid hidden, white background color
  • ticks: Coordinate grid hidden, white background color, ticks visible
sns.set_style('whitegrid')

De-spine the Plot

To remove the axis spines for the top and right axes, we use the seaborn.despine() function:

sns.despine()

By default, only the top and right axes will be despined, or have their spines removed. To despine the other two axes, we need to set the left and bottom parameters to True.

Small Multiple - FacetGrid

seaborn.FacetGrid() Reference

Small Multiple is a group of similar plots on the same scale that can be effectively compared side-by-side. In Seaborn this can be achieved in 2 steps with the seaborn.FacetGrid() function first to subset the data and create the grid, and then with FacetGrid.map() method to specify the type of plot to be generated and any shared parameters for all the subplots.

facetgrid_obj = sns.FacetGrid(dataframe_obj, col='col_name_to_condition', size=n)

facetgrid_obj.map(plot_func, col_name, shade=bool)
  • The first line creates a FacetGrid object that uses col_name_to_condition column name as a String to extract values from dataframe_obj dataframe. Parameter size specifies the height of the plot in inches.
  • Second line of code uses the facetgrid_obj to map values between col_name_to_condition and col_name visualized according to what plot_func used. The plotting function can be any valid Matplotlib or Seaborn plotting function such as sns.kdeplot or plt.hist
  • When subsetting data we can specify three conditions col, row and hue.
  • Adding a legend is done by facegrid_obj.add_legend().
Written on June 13, 2017