This notebook will give you a detailed overview of how to perform data visualization using the powerful Seaborn module in Python.
To install Seaborn type pip install seaborn or conda install seaborn in the terminal window.
Lets first look into plotting Categorical Data. Categorical data means a data column which has certain levels or categories (for example Sex column can have two distinct values - Male and Female). There are a few main plot types for this:
Let's go through examples of each!
import seaborn as sns # import the module
%matplotlib inline
tips = sns.load_dataset('tips') # tips data is available in the seaborn module which we will use for this tutorial notebook.
tips.head() # this is how the data looks like
These very similar plots allow you to get aggregate data off a categorical feature in your data. barplot is a general plot that allows you to aggregate the categorical data based off some function, by default the mean. So, in this example the mean bill for Males is around 21 dollars as compared to around 17-18 dollars for the females.
barplot = sns.barplot(x='sex',y='total_bill',data=tips,palette="Set1")
barplot.set(xlabel='Sex', ylabel='Mean Bill') # to set x and y labels
import numpy as np
In this plot we are looking for the standard deviation instead of Mean.
barplot2 = sns.barplot(x='sex',y='total_bill',data=tips,estimator=np.std,palette="Set1")
barplot2.set(xlabel='Sex', ylabel='Standard Deviation Bill')
This is essentially the same as barplot except the estimator is explicitly counting the number of occurrences. Which is why we only pass the x value:
sns.countplot(x='sex',data=tips,palette="Set1") # answers how many males and females in our data
boxplots and violinplots are used to shown the distribution of categorical data. A box plot shows the distribution of quantitative data in a way that facilitates comparisons between variables or across levels of a categorical variable. The box shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution, except for points that are determined to be “outliers” using a method that is a function of the inter-quartile range.
sns.boxplot(x="day", y="total_bill", data=tips,palette='coolwarm')
The above boxplot tells you what is the distribution of bill per day.
# Can do entire dataframe with orient='h'
sns.boxplot(data=tips,palette='coolwarm',orient='h')
sns.boxplot(x="day", y="total_bill", hue="smoker",data=tips, palette="coolwarm")
The above boxplot tells you what is the distribution of total bill per day given the person is a smoker or not.
A violin plot plays a similar role as a boxplot. It shows the distribution of quantitative data across several levels of one (or more) categorical variables such that those distributions can be compared. Unlike a box plot, in which all of the plot components correspond to actual datapoints, the violin plot features a kernel density estimation of the underlying distribution.
sns.violinplot(x="day", y="total_bill", data=tips,palette='Set2')
sns.violinplot(x="day", y="total_bill", data=tips,hue='sex',palette='Set2')
The above plot shows the distribution of total bill per day given the person is a male or a female.
sns.violinplot(x="day", y="total_bill", data=tips,hue='sex',split=True,palette='Set2')
You can use split parameter as true to have a single violin plot instead of two violin plots for each sex.
The stripplot will draw a scatterplot where one variable is categorical. A strip plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution.
The swarmplot is similar to stripplot(), but the points are adjusted (only along the categorical axis) so that they don’t overlap. This gives a better representation of the distribution of values, although it does not scale as well to large numbers of observations (both in terms of the ability to show all the points and in terms of the computation needed to arrange them).
sns.stripplot(x="day", y="total_bill", data=tips,palette = "husl")
sns.stripplot(x="day", y="total_bill", data=tips,jitter=True,palette = "deep")
sns.stripplot(x="day", y="total_bill", data=tips,jitter=True,hue='sex',palette='Set1')
The above stripplot shows the data points as per the sex.
sns.stripplot(x="day", y="total_bill", data=tips,jitter=True,hue='sex',palette='Set1',split=True)
sns.swarmplot(x="day", y="total_bill", data=tips,palette = "Paired")
sns.swarmplot(x="day", y="total_bill",hue='sex',data=tips, palette="Set1", split=True)
The above plots show swarmplots which can be used alternatively to the boxplots or violin plots.
sns.violinplot(x="tip", y="day", data=tips,palette='rainbow')
sns.swarmplot(x="tip", y="day", data=tips,color='black',size=3)
The above plot combines the violin plot and swarmplot. The violin plot gives you a visualition of the overall distribution, while the swarmplot shows each data observation.
factorplot is the most general form of a categorical plot. It can take in a kind parameter to adjust the plot type:
sns.factorplot(x='sex',y='total_bill',data=tips,kind='bar')
The factorplot is same as the barplot which we saw earlier.
Next in the notebook, let's discuss some plots that allow us to visualize the distribution of a data set. These plots are:
We will use the same tips data for the demonstration.
tips.head() # lets look again at the tips data
The distplot shows the distribution of a univariate set of observations.
sns.distplot(tips['total_bill'],color="b",hist=True) # this plot shows a histogram with an overlayed density plot.
sns.distplot(tips['total_bill'],kde=False,color="b") # if you dont want overlayed density, use kde = false
jointplot() allows you to plot for bivariate data with your choice of what kind parameter to compare with:
sns.jointplot(x='total_billhttp://localhost:8888/notebooks/Desktop/Data%20Science/DataScience_Python/Python-for-Data-Visualization/Seaborn/Seaborn%20Notebook.ipynb#',y='tip',data=tips,kind='scatter')
The above plot shows a scatterplot for total_bill and tip.
sns.jointplot(x='total_bill',y='tip',data=tips,kind='hex')
You can specify the kind = "hex" to get a hex plot. This plot could be useful if you have many data points.
sns.jointplot(x='total_bill',y='tip',data=tips,kind='reg')
You can also use kind = "reg", which will also plot a regression line in addition to the scatterplot.
pairplot will plot pairwise relationships across an entire dataframe (for the numerical columns) and supports a color hue argument (for categorical columns).
sns.pairplot(tips)
sns.pairplot(tips,hue='sex',palette='Set1')
lmplot allows you to display regression plots, and also allows you to split up those plots based off other features, as well as coloring the hue based off categorical features.
Let's explore how this works:
tips.head() # again we are using the tips data
sns.lmplot(x='total_bill',y='tip',data=tips)
The above plot shows a scatterplot between total_bill and tip and also displays the regression line.
sns.lmplot(x='total_bill',y='tip',data=tips,hue='sex',palette="Set1")
The above plot is same as the previous plot except it plots two regression lines based on the sex feature.
We can add more variable separation through columns and rows with the use of a grid. Just indicate this with the col or row arguments:
sns.lmplot(x='total_bill',y='tip',data=tips,col='sex')
So in this plot we separated the scatterplot into two columns based on the sex feature. You can do this by specifying the col parameter.
sns.lmplot(x="total_bill", y="tip", row="sex", col="time",data=tips)
We can split the scatter plot based on rows and columns as shown in this example.
sns.lmplot(x='total_bill',y='tip',data=tips,col='day',hue='sex',palette='coolwarm')
In this case we split as per the day feature (4 columns) and color is based on the sex feature.
Seaborn figures can have their size and aspect ratio adjusted with the size and aspect parameters:
sns.lmplot(x='total_bill',y='tip',data=tips,col='day',hue='sex',palette='coolwarm', aspect=0.6,size=8)
Matrix plots allow you to plot data as color-encoded matrices and can also be used to indicate clusters within the data.
Let's begin by exploring seaborn's heatmap and clustermap:
flights = sns.load_dataset('flights') # in addition with the tips data we will also use the flights data.
tips.head() # tips data
flights.head() # flights data
In order for a heatmap to work properly, your data should already be in a matrix form, the sns.heatmap function basically just colors it in for you. For example:
# The corr() function gives a matrix output of correlation coefficient of the numerical features of the data.
tips.corr()
sns.heatmap(tips.corr(),cmap="coolwarm",annot=True)
Lets consider the example for the flights data. First we will pivot the dataframe so as to make it appropriate for plotting.
flights.pivot_table(values='passengers',index='month',columns='year')
pvflights = flights.pivot_table(values='passengers',index='month',columns='year')
sns.heatmap(pvflights,cmap='coolwarm',linecolor='white',linewidths=1)
The clustermap uses hierarchal clustering to produce a clustered version of the heatmap. For example:
sns.clustermap(pvflights,cmap="coolwarm",standard_scale=1)
Notice now how the years and months are no longer in order, instead they are grouped by similarity in value (passenger count). That means we can begin to infer things from this plot, such as August and July being similar (makes sense, since they are both summer travel months)
I hope you liked this detailed overview of the seaborn module in python for data visualization. I also encourage you to look at the official documentation page for seaborn which have many examples and use cases which you could use.