Basic plots with Seaborn

Seaborn library has matplotlib at its core for data point visualizations. This library gives highly statistical informative graphics functionality to Seaborn.

Matplotlib is at the heart of Seaborn Library’s data point visualizations. This library gives highly statistically informative graphics functionality to Seaborn.

Installation

Following are short instructions for installing seaborn.

Python
Python
Python
# command prompt
pip install seaborn
# jupyter lab / collab
!pip install seaborn

You can use these commands on the command prompt. Use the same command on Jupyter or Collab in the code cell.

Importing

While importing Seaborn, you should also import the Matplotlib and pyplot objects for visualizing the plots. In the following image, we import seaborn, numpy, and pandas for visualizations, mathematical functions, and dataset handling.

Python
Python
Python
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

KDE plots with Distribution Densities

KDE plots are used to show the data distribution. In the following code, we use artificially produced data to plot with KDE.

Python
Python
Python
data = np.random.multivariate_normal([2, 3], [[4, 6], [7, 9]],size=2000)
data = pd.DataFrame(data, columns=['A', 'B'])
sns.set(rc={'figure.figsize':(11.7,8.27)})
sns.kdeplot(data['A'], shade=True)
sns.kdeplot(data['B'], shade=True)
DensityA

Distplot

Distplot can help with observing histograms with trend lines. Distplot is useful for studying continuous data.

Python
Python
Python
sns.set(rc={'figure.figsize':(11.7,8.27)})
sns.distplot(data['A']);
sns.distplot(data['B']);
DensityB

KDE plot 2D

We can also plot the data with KDE with a 2-factor distribution plot.

Python
Python
Python
sns.kdeplot(x=data['A'], y=data['B'])
kdeplot
Python
Python
Python
with sns.axes_style('white'):
    sns.jointplot("A", "B", data, kind='kde');
kdeplot2
Python
Python
Python
with sns.axes_style('white'):
    sns.jointplot("A", "B", data, kind="hex")
kdeplot3

Pairplot

Let’s use the planets dataset from Seaborn Library for rendering multiple plots in a single image. Using pair plots will help in understanding paired relations among multiple variables.

Python
Python
Python
planets = sns.load_dataset("planets")
planets.head()
methodnumberorbital periodmassdistanceyear
Radial Velocity1269.3007.1077.402006
Radial Velocity1874.7742.2156.952008
Radial Velocity1763.0002.6019.842011
Radial Velocity1326.03019.40110.622007
Radial Velocity1516.22010.50119.472009
Python
Python
Python
sns.pairplot(planets, hue='year', size=2.5);
pairplots

Jointplot

In a joint plot, we get a bivariate graph and two separate graphs placed on their respective axis to show each variable’s distribution plotted with histograms.

In total, you get three graphs,

  • one that shows the relationship between variables
  • Other two represent variables individually.
Python
Python
Python
aplanets=sns.load_dataset('geyser')
sns.jointplot("duration", "waiting", data=planets, kind='reg')
jointplot

kind parameter

We can change the kind parameter and use different arguments in the joint plot. To show an example, we will use the ‘hex’ argument with kind.

Python
Python
Python
geyser=sns.load_dataset('geyser')
with sns.axes_style('white'):
    sns.jointplot("duration", "waiting", data=geyser, kind='hex')

Factor Plot

For factor plots, we will use the taxis dataset, which has multivariate data and also has several data types. This dataset was originally published by the NYC Taxi and Limousine Commission (TLC)

Python
Python
Python
taxis = sns.load_dataset('taxis')
taxis.head(5)
PickupDrop-Off Passengers Distance FareTipTollsTotalColorPayment Pickup_Zone Dropoff_Zone Pickup_Borough dropoff_borough
3/23/2019 20:213/23/2019 20:2711.672.15012.95yellowcredit cardLenox Hill WestUN/Turtle Bay SouthManhattanManhattan
3/4/2019 16:113/4/2019 16:1910.795009.3yellowcashUpper West Side SouthUpper West Side SouthManhattanManhattan
3/27/2019 17:533/27/2019 18:0011.377.52.36014.16yellowcredit cardAlphabet CityWest VillageManhattanManhattan
3/10/2019 01:233/10/2019 01:4917.7276.15036.95yellowcredit cardHudson SqYorkville WestManhattanManhattan
3/30/2019 13:273/30/2019 13:3732.1691.1013.4yellowcredit cardMidtown EastYorkville WestManhattanManhattan
Python
Python
Python
with sns.axes_style(style='ticks'):
    g=sns.set(rc={'figure.figsize':(11.7,8.27)})
    g = sns.factorplot("color", "fare", "pickup_borough", data=taxis, kind="box")
    
    g.set_axis_labels("Taxis", "dropoff_borough");
taxis 1

Time Series Analysis

To understand time series analysis, we are using the worldwide life expectancy dataset. The first plot shows the world GDP over the years and its increase.

Python
Python
Python
lifeexp=sns.load_dataset('healthexp')
lifeexp.head(1)
YearCountrySpending UsdLife Expectancy
1970Germany252.31170.6
Python
Python
Python
with sns.axes_style('white'):
    g = sns.factorplot(x="Year",y="Spending_USD" ,data=lifeexp,aspect=4.0,)
    g.set_xticklabels(step=5)
timeseries1

Python
Python
Python
with sns.axes_style('white'):

    g = sns.factorplot(x="Year",y="Life_Expectancy" ,data=lifeexp ,aspect=2.0,)
    g.set_xticklabels(step=5)
timeseries

How useful was this post?

Click on a star to rate it!

One response to “Basic plots with Seaborn”

  1. […] Seaborn is a Python data visualization library based on Matplotlib. See how to use basic plots with seaborn here. […]

Leave a Reply

Points You Earned

Untitled design 6
0 distinction_points
Untitled design 5
python_points 0
0 Solver points
Instagram
WhatsApp
error: Content is protected !!