Seaborn Syntax
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 colorwhitegrid
: Coordinate grid displayed, white background colordark
: Coordinate grid hidden, dark background colorwhite
: Coordinate grid hidden, white background colorticks
: 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
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 fromdataframe_obj
dataframe. Parametersize
specifies the height of the plot in inches. - Second line of code uses the
facetgrid_obj
to map values betweencol_name_to_condition
andcol_name
visualized according to whatplot_func
used. The plotting function can be any valid Matplotlib or Seaborn plotting function such assns.kdeplot
orplt.hist
- When subsetting data we can specify
three
conditionscol
,row
andhue
. - Adding a legend is done by
facegrid_obj.add_legend()
.