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!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

  • 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.

  • Hypothesis Testing: A Comprehensive Overview

    This article delves into the application of hypothesis testing across diverse domains

  • Versions of ANCOVA (Analysis Of Covariance) with python

    To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating Average rating 0 / 5. Vote count: 0 No votes so far! Be the first to rate this post.

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python Functions

    Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…

  • Quiz Challenge: Basics with Python [Questions]

    Solve These Questions in Following Challange

  • Introducing Plethora of Stable Diffusion models: Part 1

    Generate AI images as good as DALL-E completely offline.

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