All IT Courses 50% Off
Data Science using Python Tutorials

Visualizing univariate distributions using seaborn

An early step in any effort to analyze data should be to understand how the variables are distributed. Techniques for distribution visualization can provide quick answers to many important questions such as.  

  • What range do the observations cover? 
  • What is their central tendency? 
  • Are they heavily skewed in one direction?  
  • Is there evidence for bimodality? 
  • Are there significant outliers?
  • Do the answers to these questions vary across subsets defined by other variables? 

There are several distribution plots designed to answer all these questions such as these. 

  • histplot()  
  • displot()  
  • kdeplot()  
  • ecdfplot()  
  • rugplot() 

There are several different approaches to visualizing a distribution, and each has its relative advantages and drawbacks. It is important to understand these factors so that you can choose the best approach for your particular aim. 

Now we try to plot all these plots and perform data analysis. In order to perform this analysis, we will use the seaborn load_dataset()  function and use it to build a dataset for our analysis. 

Now we will import all the necessary libraries

import pandas as pd  
import numpy as np  
import seaborn as sns  
df = sns.load_dataset("penguins")  df.head()  

Output:

speciesislandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsex
0AdelieTorgersen39.118.7181.03750.0Male
1AdelieTorgersen39.517.4186.03800.0Female
2AdelieTorgersen40.318.0195.03250.0Female
4AdelieTorgersen36.719.3193.03450.0Female
5AdelieTorgersen39.320.6190.03650.0Male

Histograms  

Perhaps the most common approach to visualizing a distribution is the histogram. This is the default approach in displot(), which uses the same underlying code as histplot().  

A histogram is a bar plot where the axis representing the data variable  is divided into a set of discrete bins and the count of observations  falling within each bin is shown using the height of the corresponding  

sns.displot(df, x=“flipper_length_mm")

or

sns.histplot(df, x=“flipper_length_mm")

Output: 

Visualizing univariate distributions using seaborn

This plot immediately affords a few insights about the  flipper_length_mm variable. For instance, we can see that the most common flipper length is about 195 mm, but the distribution appears bimodal, so this one number does not represent the data well. 

Choosing the bin size  

The size of the bins is an important parameter, and using the wrong bin size can mislead by obscuring important features of the data or by creating apparent features out of random variability. By default,  displot() / histplot() choose a default bin size based on the variance of the data and the number of observations.  

But you should not be over-reliant on such automatic approaches,  because they depend on particular assumptions about the structure of your data.  

It is always advisable to check that your impressions of the distribution are consistent across different bin sizes. To choose the size directly, set  the bin-width parameter 

sns.displot(df, x="flipper_length_mm",bins=30) 

Output: 

Conditioning on other variables  

Once you understand the distribution of a variable, the next step is often to ask whether features of that distribution differ across other variables in the dataset. For example, what accounts for the bimodal distribution of flipper lengths that we saw above?  

displot() and histplot() provide support for conditional subsetting via the hue semantic. Assigning a variable to a hue will draw a  separate histogram for each of its unique values and distinguish them  by color 

sns.displot(df, x=“flipper_length_mm”,hue='species')  or sns.histplot(df, x=“flipper_length_mm”,hue='species') 

Output: 

KDE plot ( Kernel density estimation )  

A histogram aims to approximate the underlying probability density function that generated the data by binning and counting observations.  Kernel density estimation (KDE) presents a different solution to the same problem. Rather than using discrete bins, a KDE plot smooths the  observations with a Gaussian kernel, producing a continuous density  estimate 

sns.displot(df, x="flipper_length_mm", kind=“kde")

Visualizing univariate distributions using seaborn

Choosing the smoothing bandwidth  

Much like with the bin size in the histogram, the ability of the KDE to accurately represent the data depends on the choice of smoothing bandwidth. An over-smoothed estimate might erase meaningful features, but an under-smoothed estimate can obscure the true shape within random noise. The easiest way to check the robustness of the  estimate is to adjust the default bandwidth 

sns.displot(df, x=“flipper_length_mm", kind=“kde",  bw_adjust=.25)  

Output:  

Visualizing univariate distributions using seaborn

Conditioning on other variables  

As with histograms, if you assign a hue variable, a separate density  estimate will be computed for each level of that variable

sns.displot(df, x=“flipper_length_mm”, kind=“kde",  hue=‘species’)  

Output: 

Visualizing univariate distributions using seaborn

In many cases, the layered KDE is easier to interpret than the layered  histogram, so it is often a good choice for the task of comparison As a compromise, it is possible to combine these two approaches.  While in histogram mode, displot() also with histplot() has the  option of including the smoothed KDE curve (note kde=True, not  kind=“kde”) 

sns.displot(df, x=“flipper_length_mm",kde=True)

Output:

Visualizing univariate distributions using seaborn

ECDF plots ( “empirical cumulative distribution function)  

A third option for visualizing distributions computes the “empirical cumulative distribution function” (ECDF). This plot draws a  monotonically-increasing curve through each data point such that the  height of the curve reflects the proportion of observations with a smaller  value: 

sns.displot(penguins, x=“flipper_length_mm”,  kind="ecdf") 

or 

sns.ecdfplot(penguins, x=“flipper_length_mm”)

Output: 

Visualizing univariate distributions using seaborn

The ECDF plot has two key advantages. Unlike the histogram or KDE, it directly represents each data point. That means there is no bin size or smoothing parameter to consider. Additionally, because the curve is  monotonically increasing, it is well-suited for comparing multiple  distributions

sns.displot(penguins, x=“flipper_length_mm”,  kind=“ecdf", hue=“species")  

Output:  

Visualizing univariate distributions using seaborn

The major downside to the ECDF plot is that it represents the shape of the distribution less intuitively than a histogram or density curve.  Consider how the bimodality of flipper lengths is immediately apparent in the histogram, but to see it in the ECDF plot, you must look for varying slopes. Nevertheless, with practice, you can learn to answer all of the important questions about distribution by examining the ECDF,  and doing so can be a powerful approach. 

Rug plot  

The rug is not a separate plot. It is a one-dimensional display that you can add to existing plots to illuminate information that is sometimes lost in other types of graphs. Like a strip plot, it represents values of a variable by putting a symbol at various points along an axis.  However, it uses short lines to represent points. You can place it at the  bottom (the default) or top of a graph (side = 3)

sns.displot(df,x=“flipper_length_mm”,kind=“kde”,  rug=True)  

Output: 

In the next article we will learn how to visualize bivariate distributions

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close

Get Python Course
worth 499$ for FREE!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys Blog will use the information you provide on this form to be in touch with you and to provide updates and marketing.