Seaborn essentials for data visualization in Python | by Mahbubul Alam | Towards Data Science

As I said before, the purpose of data visualization is to communicate hidden information in the data. Visualization fundamentally serves 4 purposes in data science, in understanding:
the distribution of features
relationships between two or more variables
comparisons between variables
the composition of data
Various ways you can identify and communicate that hidden information and there are tools to do exactly that. Regardless of which programming language you choose, each language has libraries to handle data visualization efficiently.
If you are in Python you have several options, but I’ve found seaborn to be best in town. Not because seaborn can do something that other libraries cann’t, but because of its simplicity and intuitive code structure.
So the purpose of this article is to demonstrate some use cases of Seaborn with code snippets. My learning/teaching philosophy is to start with a problem and then find tools that can solve it. So I am not going to show everything under the sun, rather give an intuition on how Seaborn works and how to solve the 4 categories of problems I just mentioned.
Let’s dive right in.
seaborn comes with 17 built-in datasets. That means you don’t have to spend a whole lot of your time finding the right dataset and cleaning it up to make Seaborn-ready; rather you will focus on the core features of Seaborn visualization techniques to solve problems.
First, let’s take a look at the datasets.
# get names of the builtin datasetsns.get_dataset_names()
If you are in data science for some time you’ll recognize many of them just by their names (titanic? iris?). Otherwise, just load the dataset and call the head() function to take a peek into the data.
df = sns.load_dataset("iris")df.head()
I’m going to use a few of those datasets to show different kinds of visualization techniques, so I’m loading them all in. If you know what each dataset is about that’s great, otherwise don’t bother. Just know that each dataset contains variables of different kinds; some of them are discrete variables (e.g. 10, 20 , 30 miles/gallon), some are continuous (e.g. 5.2, 3.6 petal length) and some are categorical (e.g. days of the week). Knowing just different variable types and when to use them should work for now.
# loading additional datasetstips = sns.load_dataset("tips")mpg = sns.load_dataset("mpg")fmri = sns.load_dataset("fmri")car_crashes = sns.load_dataset("car_crashes")
Our first kind of problem is to understand the distribution of data. By distribution I mean few things: frequency distribution, probability distribution or just spread of the data with respect to central values (mean, median etc).
Histogram
Let’s say we have a dataset containing 1000 cars and their fuel efficiency in miles per gallon (mpg). A histogram will tell us the frequency distribution of the number of cars in each mpg category.
# Bar histogramsns.distplot(mpg["mpg"], kde = False)
There is a more sophisticated version of this frequency distribution used in statistics called the probability distribution. You can plot that as well.
# Line histogram/kernel density plotsns.kdeplot(mpg["mpg"], shade = True)
There is another kind of distribution — better known as spread— which shows how a variable is dispersed/spread with respect to its central tendency.
Boxplot is best known to demonstrate the dispersion of a variable with values such as the median, the minimum, the maximum and the outliers — all in the same plot.
# boxplotsns.boxplot(y = mpg["mpg"])
Kids grow taller with age — that’s a relationship between two variables: height and age.
The bigger the house, the higher the price — that’s another kind of relationship between the variables: floor size and price.
Relational plots display how variables are associated with each other.
Visualization can examine and plot the association between variables. For continuous variables, you can pretty much visualize anything in a scatterplot and visually determine the relationship between them.
# scatterplotsns.scatterplot(x = "sepal_length", y = "petal_length", data = iris)
You can see from the scatterplot below that in Iris flowers high petal length is positively associated with sepal length.
If you are having trouble visually figuring out the relationship, there’s another option — drawing a trend line.
# trend linesns.lmplot(x = "sepal_length", y = "petal_length", data = iris, scatter = False)
The trend line below is applied to the same data as the previous one in the scatter plot. Which one you want to use depends on your needs, but there are tradeoffs. In the scatterplot, you see the variability of every single data point in a two-dimensional space, but not easy to track the trend.
In a trend plot — created based on a linear model — you can identify the overall trend in data along with confidence intervals, but you lose individual data points (but of course you can display points in trend plots as well).
The comparative analysis is key to many business decisions. Which product is selling better — product A or product B? Is there a significant difference between the two drugs in their effectiveness? These kinds of questions are asked all the time all across the decision-making landscape.
Bar charts are some of the simplest and old school yet effective visualization techniques to communicate comparative analysis. The figure below presents the total restaurant bills paid by customers on different days of the week. So this visual compares total bills between weekdays.
# bar chartsns.barplot(x = "day", y = "total_bill", data = tips)
Line charts are another way to compare data. It’s commonly used in time series analysis where the temporal evolution of two sets of observations is compared.
# line chart/time seriessns.lineplot(x="timepoint", y="signal", hue="event", data=fmri)
The final pillar of data visualization is composition. The purpose of composition charts is to show the composition of one or more variables in absolute and relative terms (e.g. percentage).
Composition charts are a bit complicated to create in Seaborn, it’s not a one-liner code like the others. So bear with me as I give two examples below.
Stacked charts show the composition of a variable with different categories in a single bar. For example, a bar showing total car crashes in the state of Alabama, which is also disaggregated by crashes that involved alcohol (see the figure below).
# Initialize the matplotlib figuref, ax = plt.subplots(figsize=(10, 15))# Plot the total crashessns.set_color_codes("pastel")sns.barplot(x="total", y="abbrev", data=crashes,label="Total", color="b")# Plot the crashes where alcohol was involvedsns.set_color_codes("muted")sns.barplot(x="alcohol", y="abbrev", data=crashes, label="Alcohol-involved", color="b")# Add a legend and informative axis labelax.legend(ncol=2, loc="upper right", frameon=True)
Stacked area charts display the changes in values of different groups of observation in the same plot area. In this case, the values are “stacked” on top of each other.
Seaborn’s built-in datasets and codes are not quite useful to display stacked area charts, so we are going to create a simple dataset and display a “Seaborn-style” graph using matplotlib library.
# stacked areaimport numpy as npimport matplotlib.pytplot as plt# Datax = range(1,6)y = [[2,4,5,6,8], [2,3,6,7,10], [2,6,7,8,5]]# Plotplt.stackplot(x,y, labels=['X','Y','Z'])plt.legend(loc='upper left')plt.show()
The purpose of this article was to demonstrate some visualization techniques using the Python library seaborn. I wanted to cover two things — introduce different kinds of visualizations you will typically encounter in data science and second, some code snippets using Seaborn’s built-in datasets. Hope that was useful. Shout out if you want to see more articles like this.