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!

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • ANOVA (Analysis of Variance ) part 1

    A method to find a statistical relationship between two variables in a dataset where one variable is used to group data.

  • 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 in python

    The Matplotlib library helps you create static and dynamic visualisations. Dynamic visualizations that are animated and interactive. This library makes it easy to plot data and create graphs.

  • Plotly with Python and R

    This library is named Plotly after the company of the same name. Plotly provides visualization libraries for Python, R, MATLAB, Perl, Julia, Arduino, and REST.

  • Numpy Array

    Numpy array have functions for matrices ,linear algebra ,Fourier Transform. Numpy arrays provide 50x more speed than a python list.

  • NumPy: Python’s Mathematical Backbone

    Numpy has created a vast ecosystem spanning numerous fields of science.

  • Introduction to Pandas: A Guide

    Pandas is a easy to use data analysis and manipulation tool. Pandas provides functionality for categorical,ordinal, and time series data . Panda provides fast and powerful calculations for data analysis.

  • Pandas Dataframe in brief

    In this tutorial, you will learn How to Access The Data in Various Ways From the dataframe.

  • Exploring the World of Sets in Python

    Understand one of the important data types in Python. Each item in a set is distinct. Sets can store multiple items of various types of data.

  • A Beginner’s Guide to Immutable Tuples

    Tuples are a sequence of Python objects. A tuple is created by separating items with a comma. They are put inside the parenthesis “”(“” , “”)””.

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 !!