0% found this document useful (0 votes)
18 views76 pages

Numpy 4

The document provides an overview of the Seaborn library in Python, focusing on its capabilities for creating various types of categorical plots, including catplots, bar plots, and box plots. It explains the syntax and parameters for the catplot function, along with examples demonstrating how to visualize categorical data effectively. Additionally, it covers customization options for plots such as changing axis labels, setting titles, and adjusting figure sizes.

Uploaded by

virajsawant0293
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views76 pages

Numpy 4

The document provides an overview of the Seaborn library in Python, focusing on its capabilities for creating various types of categorical plots, including catplots, bar plots, and box plots. It explains the syntax and parameters for the catplot function, along with examples demonstrating how to visualize categorical data effectively. Additionally, it covers customization options for plots such as changing axis labels, setting titles, and adjusting figure sizes.

Uploaded by

virajsawant0293
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Search...

Tutorials
Practice V
Jobs
Python for Machine Learning Machine Learning with R Machine Learning Algorithms EDA Math for Machine Learning Machine Learning Inte

Python Seaborn - Catplot


Last Updated : 26 Nov, 2020

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface
for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major
problems faced by Matplotlib; the problems are?
Default Matplotlib parameters
Working with data frames

As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know
Matplotlib, you are already half-way through Seaborn. Seaborn library offers many advantages over
other plotting libraries:
It is very easy to use and requires less code syntax
Works really well with `pandas` data structures, which is just what you need as a data scientist.
It is built on top of Matplotlib, another vast and deep data visualization library.

Syntax: [Link](*, x=None, y=None, hue=None, data=None, row=None, col=None,


kind='strip', color=None, palette=None, **kwargs)

Parameters

x, y, hue: names of variables in data


Inputs for plotting long-form data. See examples for interpretation.
data: DataFrame
Long-form (tidy) dataset for plotting. Each column should correspond to a variable, and each
row should correspond to an observation.
row, col: names of variables in data, optional
Categorical variables that will determine the faceting of the grid.
kind: str, optional
The kind of plot to draw, corresponds to the name of a categorical axes-level plotting
function. Options are: “strip”, “swarm”, “box”, “violin”, “boxen”, “point”, “bar”, or “count”.
color: matplotlib color, optional
Color for all of the elements, or seed for a gradient palette.
palette: palette name, list, or dict
Colors to use for the different levels of the hue variable. Should be something that can be
interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors.
kwargs: key, value pairings
Other keyword arguments are passed through to the underlying plotting function.
Examples:
If you are working with data that involves any categorical variables like survey responses, your best
tools to visualize and compare different features of your data would be categorical plots. Plotting
categorical plots it is very easy in seaborn. In this example x,y and hue take the names of the features
in your data. Hue parameters encode the points with different colors with respect to the target
variable.

import seaborn as sns

exercise = sns.load_dataset("exercise")
g = [Link](x="time", y="pulse",
hue="kind",
data=exercise)

Output:

For the count plot, we set a kind parameter to count and feed in the data using data parameters. Let's
start by exploring the time feature. We start off with catplot() function and use x argument to specify
the axis we want to show the categories.

import seaborn as sns

sns.set_theme(style="ticks")
exercise = sns.load_dataset("exercise")

g = [Link](x="time",
kind="count",
data=exercise)

Output:

Another popular choice for plotting categorical data is a bar plot. In the count plot example, our plot
only needed a single variable. In the bar plot, we often use one categorical variable and one
quantitative. Let’s see how the time compares to each other.

import seaborn as sns


exercise = sns.load_dataset("exercise")
g = [Link](x="time",
y="pulse",
kind="bar",
data=exercise)

Output:

For creating the horizontal bar plot we have to change the x and y features. When you have lots of
categories or long category names it's a good idea to change the orientation.

import seaborn as sns

exercise = sns.load_dataset("exercise")
g = [Link](x="pulse",
y="time",
kind="bar",
data=exercise)

Output:

Use a different plot kind to visualize the same data:

import seaborn as sns

exercise = sns.load_dataset("exercise")

g = [Link](x="time",
y="pulse",
hue="kind",
data=exercise,
kind="violin")

Output:
import seaborn as sns

exercise = sns.load_dataset("exercise")

g = [Link](x="time",
y="pulse",
hue="kind",
col="diet",
data=exercise)

Output:

Make many column facets and wrap them into the rows of the grid. The aspect will change the width
while keeping the height constant.

titanic = sns.load_dataset("titanic")
g = [Link](x="alive", col="deck", col_wrap=4,
data=titanic[[Link]()],
kind="count", height=2.5, aspect=.8)

Output:

Plot horizontally and pass other keyword arguments to the plot function:

g = [Link](x="age", y="embark_town",
hue="sex", row="class",
data=titanic[titanic.embark_town.notnull()],
orient="h", height=2, aspect=3, palette="Set3",
kind="violin", dodge=True, cut=0, bw=.2)

Output:
Box plots are visuals that can be a little difficult to understand but depict the distribution of data very
beautifully. It is best to start the explanation with an example of a box plot. I am going to use one of
the common built-in datasets in Seaborn:

tips = sns.load_dataset('tips')
[Link](x='day',
y='total_bill',
data=tips,
kind='box');

Output:

Outlier Detection Using Box Plot:

The edges of the blue box are the 25th and 75th percentiles of the distribution of all bills. This
means that 75% of all the bills on Thursday were lower than 20 dollars, while another 75% (from
the bottom to the top) was higher than almost 13 dollars. The horizontal line in the box shows the
median value of the distribution.
Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%
The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQR
The upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR
Comment V vivekpi… Follow 2

Article Tags: Machine Learning AI-ML-DS python Python-Seaborn

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

How To Make Ridgeline plot in Python with Seaborn?


Last Updated : 23 Jul, 2025

Prerequisite: Seaborn
Ridgeline plot is a set of overlapped density plots that help in comparing multiple distributions
among datasets. The Ridgeline plots look like a mountain range, they can be quite useful for
visualizing changes in distributions over time or space. Sometimes it is also known as "joyplot", in
reference to the iconic cover art for Joy Division’s album Unknown Pleasures. In this article, We will
see how to generate Ridgeline plots for the dataset.

Installation

Like any another python library, seaborn can be easily installed using pip:

pip install seaborn

This library is a part of Anaconda distribution and usually works just by import if your IDE is
supported by Anaconda, but it can be installed too by the following command:

conda install seaborn

Procedure
Load the packages required to generate the Ridgeline plot with Python.
Read the Dataset. In this example, we use the read_csv() method to load the dataset. In the given
example we will only display the top 5 entries using the head() method.
Generate RidgePlot. The Ridgeline Plot uses faceting meaning it creates small multiples, in a
single column. To generate Ridgeline Plot Seaborn uses FacetGrid() method and all required
information should be passed to it

Syntax: [Link](data, row, col, hue, palette, aspect, height)

Parameters:

1. data: Tidy (“long-form”) dataframe where each column is a variable and each row is an
observation.
2. row, col, hue: Variables that define subsets of the data, which will be drawn on separate
facets in the grid.
3. height: Height (in inches) of each facet.
4. aspect: Aspect ratio of each facet, so that aspect * height gives the width of each facet in
inches.
5. palette: Colors to use for the different levels of the hue variable.
Use the map() method to creates a density plot in each element of the grid. In this example, we
need a density plot so use kdeplot() method which available in Seaborn.

Sample Database: Dataset used in the following example is downloaded from [Link]. The
following link can be used for the same.
Example:

import seaborn as sns


import [Link] as plt
import pandas as pd
from sklearn import preprocessing

df = pd.read_csv("titanic_train.csv")
[Link]()

le = [Link]()
df["Sex"] = le.fit_transform(df["Sex"])

rp = [Link](df, row="Sex", hue="Sex", aspect=5, height=1.25)

[Link]([Link], 'Survived', clip_on=False,


shade=True, alpha=0.7, lw=4, bw=.2)

[Link]([Link], y=0, lw=4, clip_on=False)

Output :

Comment A abhijit… Follow

Article Tags: Python Python-Seaborn

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Technologies
Software and
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

Change Axis Labels, Set Title and Figure Size to Plots with Seaborn
Last Updated : 23 Jul, 2025

Seaborn is Python's visualization library built as an extension to Matplotlib. Seaborn has Axes-level
functions (scatterplot, regplot, boxplot, kdeplot, etc.) as well as Figure-level functions (lmplot,
factorplot, jointplot, relplot etc.). Axes-level functions return Matplotlib axes objects with the plot
drawn on them while figure-level functions include axes that are always organized in a meaningful
way. The basic customization that a graph needs to make it understandable is setting the title,
setting the axis labels, and adjusting the figure size. Any customization made is on the axes object for
axes-level functions and the figure object for figure-level functions.
Note: Axes in the above explanation refers to a part of the figure or the top layer of a figure and is
not the mathematical term for more than one axis. Consider a plot on a figure. This plot axes. Now,
consider multiple subplots on a figure. Each of these subplots is one axes.
Let us see some examples to better understand customization with Seaborn.

# Import required libraries


import [Link] as plt
import seaborn as sns

# Load data set


tips = sns.load_dataset( "tips" )
[Link]()

Output:

Example 1: Customizing plot with axes object


For axes-level functions, pass the figsize argument to the [Link]() function to set the figure size.
The function [Link]() returns Figure and Axes objects. These objects are created ahead of time
and later the plots are drawn on it. We make use of the set_title(), set_xlabel(), and set_ylabel()
functions to change axis labels and set the title for a plot. We can set the size of the text with size
attribute. Make sure to assign the axes-level object while creating the plot. This object is then used
for setting the title and labels as shown below.

# Set figure size (width, height) in inches


fig, ax = [Link](figsize = ( 5 , 3 ))

# Plot the scatterplot


[Link]( ax = ax , x = "total_bill" , y = "tip" , data = tips )

# Set label for x-axis


ax.set_xlabel( "Total Bill (USD)" , size = 12 )

# Set label for y-axis


ax.set_ylabel( "Tips (USD)" , size = 12 )

# Set title for plot


ax.set_title( "Bill vs Tips" , size = 24 )
# Display figure
[Link]()

Output:

Example 2: Customizing scatter plot with pyplot object


We can also change the axis labels and set the plot title with the [Link] object using
xlabel(), ylabel() and title() functions. Similar to the above example, we can set the size of the text
with the size attribute. The function [Link]() creates a Figure instance and the figsize argument
allows to set the figure size.

# Set figure size (width, height) in inches


[Link](figsize = ( 5 , 3 ))

# Plot scatterplot
[Link]( x = "total_bill" , y = "tip" , data = tips )

# Set label for x-axis


[Link]( "Total Bill (USD)" , size = 12 )

# Set label for y-axis


[Link]( "Tips (USD)" , size = 12 )

# Set title for figure


[Link]( "Bill vs Tips" , size = 24 )

# Display figure
[Link]()

Output:

Example 3: Customizing multiple plots in the same figure


Seaborn's relplot function returns a FacetGrid object which is a figure-level object. This object allows
the convenient management of subplots. To give a title to the complete figure containing multiple
subplots, we use the suptitle() method. The subplots_adjust() method is used to avoid overlapping of
subplot titles and the figure title by specifying the top, bottom, left, and right edge positions of the
subplots. To set the figure size, pass a dictionary with the key '[Link]' in the set() method. The
set() method allows to set multiple theme parameters in a single step.

# Set figure size


[Link]( rc = {'[Link]' : ( 20, 20 ),
'[Link]' : 12 })

# Plot scatter plot


g = [Link](data = tips , x = "total_bill" ,
y = "tip" , col = "time" ,
hue = "day" , style = "day" ,
kind = "scatter" )

# Title for the complete figure


[Link]("Tips by time of day" ,
fontsize = 'x-large' ,
fontweight = 'bold' )

# Adjust subplots so that titles don't overlap


[Link].subplots_adjust( top = 0.85 )

# Set x-axis and y-axis labels


g.set_axis_labels( "Tip" , "Total Bill (USD)" )

# Display the figure


[Link]()

Output:

Comment A akshis… Follow 0

Article Tags: Python Python-Seaborn

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

How To Place Legend Outside the Plot with Seaborn in Python?


Last Updated : 16 Nov, 2020

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface
for drawing attractive and informative statistical graphics. Basically, it helps us stylize our basic plot
made using matplotlib. Moreover, it also provides us different plotting techniques to ease our
Exploratory Data Analysis(EDA). With these plots, it also becomes important to provide legends for
a particular plot.
In this following article, we are going to see how can we place our Legend on our plot, and later in
this article, we will also see how can we place the legend outside the plot using Seaborn.
We will start by importing our necessary libraries.

import seaborn as sns


import [Link] as plt

We will be using Seaborn for not only plotting the data but also importing our dataset. Here we will
be using the Gamma dataset by seaborn.

# set our graph style to whitegrid


[Link](style="whitegrid")

# load the gammas dataset


ds = sns.load_dataset("gammas")

# use seaborn's lineplot to plot our timeplot


# and BOLD signal columns
[Link](data=ds, x="timepoint", y="BOLD signal", hue = "ROI")

[Link]()

Output:
We can see that this plots a beautiful line plot graph with the legends. We can see that the legend
box is on the plot. This might be an issue in many plots, so we need to keep our legend box outside
the plot.
We can do this by using matplotlib's legend function and providing its necessary parameters.

[Link](bbox_to_anchor=(1, 1), loc=2)

Output:

We can also tune our parameters according to our necessities.

[Link](bbox_to_anchor=(1.02, 1), loc=2)

Output:

Hence, this technique can be used in many scenarios where the legend box comes on the graph
which may be otherwise useful for our EDA.

Comment A ayush… Follow 1

Article Tags: Python Python-Seaborn


Company Explore Tutorials Courses Offline Preparation
About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

How to Plot a Confidence Interval in Python?


Last Updated : 23 Jul, 2025

Confidence Interval is a type of estimate computed from the statistics of the observed data which
gives a range of values that's likely to contain a population parameter with a particular level of
confidence.
A confidence interval for the mean is a range of values between which the population mean possibly
lies. If I'd make a weather prediction for tomorrow of somewhere between -100 degrees and +100
degrees, I can be 100% sure that this will be correct. However, if I make the prediction to be between
20.4 and 20.5 degrees Celsius, I'm less confident. Note how the confidence decreases, as the interval
decreases. The same applies to statistical confidence intervals, but they also rely on other factors.
A 95% confidence interval, will tell me that if we take an infinite number of samples from my
population, calculate the interval each time, then in 95% of those intervals, the interval will contain
the true population mean. So, with one sample we can calculate the sample mean, and from there
get an interval around it, that most likely will contain the true population mean.

Area under the two black lines shows the 95% confidence interval

Confidence Interval as a concept was put forth by Jerzy Neyman in a paper published in 1937. There
are various types of the confidence interval, some of the most commonly used ones are: CI for mean,
CI for the median, CI for the difference between means, CI for a proportion and CI for the difference in
proportions.
Let's have a look at how this goes with Python.
Computing C.I given the underlying distribution using lineplot()
The lineplot() function which is available in Seaborn, a data visualization library for Python is best to
show trends over a period of time however it also helps in plotting the confidence interval.
Syntax:

[Link](x=None, y=None, hue=None, size=None, style=None, data=None, palette=None,


hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None,
dashes=True, markers=None, style_order=None, units=None, estimator='mean', ci=95,
n_boot=1000, sort=True, err_style='band', err_kws=None, legend='brief', ax=None, **kwargs,)

Parameters:
x, y: Input data variables; must be numeric. Can pass data directly or reference columns in
data.
hue: Grouping variable that will produce lines with different colors. Can be either categorical
or numeric, although color mapping will behave differently in latter case.
style: Grouping variable that will produce lines with different dashes and/or markers. Can
have a numeric dtype but will always be treated as categorical.
data: Tidy ("long-form") dataframe where each column is a variable and each row is an
observation.
markers: Object determining how to draw the markers for different levels of the style
variable.
legend: How to draw the legend. If "brief", numeric ``hue`` and ``size`` variables will be
represented with a sample of evenly spaced values.

Return: The Axes object containing the plot.

By default, the plot aggregates over multiple y values at each value of x and shows an estimate of
the central tendency and a confidence interval for that estimate.
Example:

# import libraries
import numpy as np
import seaborn as sns
import [Link] as plt

# generate random data


[Link](0)
x = [Link](0, 30, 100)
y = x+[Link](0, 1, 100)

# create lineplot
ax = [Link](x, y)

In the above code, variable x will store 100 random integers from 0 (inclusive) to 30 (exclusive) and
variable y will store 100 samples from the Gaussian (Normal) distribution which is centred at 0 with
spread/standard deviation 1. NumPy operations are usually done on pairs of arrays on an element-
by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the
above example. Finally, a lineplot is created with the help of seaborn library with 95% confidence
interval by default. The confidence interval can easily be changed by changing the value of the
parameter 'ci' which lies within the range of [0, 100], here I have not passed this parameter hence it
considers the default value 95.
The light blue shade indicates the confidence level around that point if it has higher confidence the
shaded line will be thicker.

Computing C.I. given the underlying distribution using regplot()


The [Link]() helps to plot data and a linear regression model fit. This function also allows
plotting the confidence interval.
Syntax:

[Link]( x, y, data=None, x_estimator=None, x_bins=None, x_ci='ci', scatter=True,


fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False,
robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True,
x_jitter=None, y_jitter=None, label=None, color=None, marker='o', scatter_kws=None,
line_kws=None, ax=None)

Parameters: The description of some main parameters are given below:

x, y: These are Input variables. If strings, these should correspond with column names in
"data". When pandas objects are used, axes will be labeled with the series name.
data: This is dataframe where each column is a variable and each row is an observation.
lowess: (optional) This parameter take boolean value. If "True", use "statsmodels" to
estimate a nonparametric lowess model (locally weighted linear regression).
color: (optional) Color to apply to all plot elements.
marker: (optional) Marker to use for the scatterplot glyphs.

Return: The Axes object containing the plot.

Basically, it includes a regression line in the scatterplot and helps in seeing any linear relationship
between two variables. Below example will show how it can be used to plot confidence interval as
well.
Example:

# import libraries
import numpy as np
import seaborn as sns
import [Link] as plt

# create random data


[Link](0)
x = [Link](0, 10, 10)
y = x+[Link](0, 1, 10)

# create regression plot


ax = [Link](x, y, ci=80)

The regplot() function works in the same manner as the lineplot() with a 95% confidence interval by
default. Confidence interval can easily be changed by changing the value of the parameter 'ci' which
lies in the range of [0, 100]. Here I have passed ci=80 which means instead of the default 95%
confidence interval, an 80% confidence interval is plotted.

The width of light blue color shade indicates the confidence level around the regression line.
Computing C.I. using Bootstrapping
Bootstrapping is a test/metric that uses random sampling with replacement. It gives the measure of
accuracy (bias, variance, confidence intervals, prediction error, etc.) to sample estimates. It allows the
estimation of the sampling distribution for most of the statistics using random sampling methods. It
may also be used for constructing hypothesis tests.
Example:

# import libraries
import pandas
import numpy
from [Link] import resample
from [Link] import accuracy_score
from matplotlib import pyplot as plt

# load dataset
x = [Link]([180,162,158,172,168,150,171,183,165,176])

# configure bootstrap
n_iterations = 1000 # here k=no. of bootstrapped samples
n_size = int(len(x))

# run bootstrap
medians = list()
for i in range(n_iterations):
s = resample(x, n_samples=n_size);
m = [Link](s);
[Link](m)
# plot scores
[Link](medians)
[Link]()

# confidence intervals
alpha = 0.95
p = ((1.0-alpha)/2.0) * 100
lower = [Link](medians, p)
p = (alpha+((1.0-alpha)/2.0)) * 100
upper = [Link](medians, p)

print(f"\n{alpha*100} confidence interval {lower} and {upper}")


After importing all the necessary libraries create a sample S with size n=10 and store it in a variable
x. Using a simple loop generate 1000 artificial samples (=k) with each sample size m=10 (since
m<=n). These samples are called the bootstrapped sample. Their medians are computed and stored
in a list 'medians'. Histogram of Medians from 1000 bootstrapped samples is plotted with the help of
matplotlib library and using the formula confidence interval of a sample statistic calculates an upper
and lower bound for the population value of the statistic at a specified level of confidence based on
sample data is calculated.

95.0 confidence interval lies between 161.5 and 176.0

Comment S swapni… Follow 2

Article Tags: Technical Scripter Python Technical Scripter 2020 Python-matplotlib +2 More

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Technologies
Software and
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

How to Make a Time Series Plot with Rolling Average in Python?


Last Updated : 2 Dec, 2020

Time Series Plot is used to observe various trends in the dataset over a period of time. In such
problems, the data is ordered by time and can fluctuate by the unit of time considered in the dataset
(day, month, seconds, hours, etc.). When plotting the time series data, these fluctuations may prevent
us to clearly gain insights about the peaks and troughs in the plot. So to clearly get value from the
data, we use the rolling average concept to make the time series plot.
The rolling average or moving average is the simple mean of the last 'n' values. It can help us in
finding trends that would be otherwise hard to detect. Also, they can be used to determine long-term
trends. You can simply calculate the rolling average by summing up the previous 'n' values and
dividing them by 'n' itself. But for this, the first (n-1) values of the rolling average would be Nan.
In this article, we will learn how to make a time series plot with a rolling average in Python using
Pandas and Seaborn libraries. Below is the syntax for computing rolling average using pandas.

Syntax: [Link](n).mean()

We will be using the 'Daily Female Births Dataset'. This dataset describes the number of daily
female births in California in 1959. There are 365 observations from 01-01-1959 to 31-12-1959.
You can download the dataset from this link.
Let's Implement with step-wise:
Step 1: Import the libraries.

# import the libraries


import pandas as pd
import seaborn as sns
import [Link] as plt

Step 2: Import the dataset

# import the dataset


data = pd.read_csv( "[Link] \
Datasets/master/[Link]")

#view the dataset


display( [Link]())

Output:

Step 3: Plot a simple time series plot using [Link]()


# set figure size
[Link]( figsize = ( 12, 5))

# plot a simple time series plot


# using [Link]()
[Link]( x = 'Date',
y = 'Births',
data = data,
label = 'DailyBirths')

[Link]( 'Months of the year 1959')

# setting customized ticklabels for x axis


pos = [ '1959-01-01', '1959-02-01', '1959-03-01', '1959-04-01',
'1959-05-01', '1959-06-01', '1959-07-01', '1959-08-01',
'1959-09-01', '1959-10-01', '1959-11-01', '1959-12-01']

lab = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',


'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']

[Link]( pos, lab)

[Link]('Female Births')

Output:

We can notice that it is very difficult to gain knowledge from the above plot as the data fluctuates a
lot. So, let us plot it again but using the Rolling Average concept this time.
Step 4: Compute Rolling Average using [Link]().
For rolling average, we have to take a certain window size. Here, we have taken the window size = 7
i.e. rolling average of 7 days or 1 week.

# computing a 7 day rolling average


data[ '7day_rolling_avg' ] = [Link]( 7).mean()

# viewing the dataset


Display([Link](10))

Output:
We can observe that the first 6 values of the '7day_rolling_avg' column are NaN values. This is
because these 6 values don't have enough data to compute the rolling average of 7 days. So, in the
plot also, for the first six values, no values would be plotted.
Step 5: Make a time series plot using rolling average calculated in step 4

# set figure size


[Link]( figsize = ( 12, 5))

# plot a simple time series plot


# using [Link]()
[Link]( x = 'Date',
y = 'Births',
data = data,
label = 'DailyBirths')

# plot using rolling average


[Link]( x = 'Date',
y = '7day_rolling_avg',
data = data,
label = 'Rollingavg')

[Link]('Months of the year 1959')

# setting customized ticklabels for x axis


pos = [ '1959-01-01', '1959-02-01', '1959-03-01', '1959-04-01',
'1959-05-01', '1959-06-01', '1959-07-01', '1959-08-01',
'1959-09-01', '1959-10-01', '1959-11-01', '1959-12-01']

lab = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',


'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']

[Link]( pos, lab)

[Link]('Female Births')

Output:
We can clearly see through the above graph that the rolling average has smoothened the number of
female births, and we can notice the peak more evidently.

Comment R riyaag… Follow 3

Article Tags: Technical Scripter Python Technical Scripter 2020 Python-pandas +3 More

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

How To Add Regression Line Per Group with Seaborn in Python?


Last Updated : 25 Nov, 2020

In this article, we will learn how to add a regression line per group with Seaborn in Python. Seaborn
has multiple functions to form scatter plots between two quantitative variables. For example, we can
use lmplot() function to make the required plot.
What is Regression Line?
A regression line is just one line that most closely fits the info (in terms of getting the littlest overall
distance from the road to the points). Statisticians call this system for locating the best-fitting line an
easy rectilinear regression analysis using the smallest amount squares method.

Steps Required

1. Import Library.
2. Import or create data.
3. Use lmplot method. This method is used to add a regression line per group by simply adding the
hue parameter with the categorical variable name.
4. Use different arguments for better visualization.

Example 1:

# import libraries
import seaborn

# load data
tip = seaborn.load_dataset('tips')

# use lmplot
[Link](x="total_bill",
y="size",
hue="sex",
data=tip)

Output:
Example 2:

# import libraries
import seaborn

# load data
tip = seaborn.load_dataset('tips')

# use lmplot
[Link](x="total_bill",
y="tip",
hue="day",
markers='*',
data=tip)

Output:
Example 3:

# import libraries
import seaborn

# load data
iris = seaborn.load_dataset('iris')

# use lmplot
[Link](x="sepal_length",
y="sepal_width",
hue="species",
markers='+',
data=iris)

Output:
Comment D deepa… Follow

Article Tags: Python Python-Seaborn

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
a Visualization Tutorial With Python Types Matplotlib Altair Plotly Computer Vision OpenCV Computer Graphics Tutorial Deep Learn

Data Visualization with Seaborn - Python


Last Updated : 10 Dec, 2025

Seaborn is a popular Python library for creating attractive statistical visualizations. Built on Matplotlib and
integrated with Pandas, it simplifies complex plots like line charts, heatmaps and violin plots with minimal
code.

2/4

Creating Plots with Seaborn


Seaborn makes it easy to create clear and informative statistical plots with just a few lines of code. It offers
built-in themes, color palettes, and functions tailored for different types of data.

Let’s see various types of plots with simple code to understand how to use it effectively.

1. Line plot

A line plot shows the relationship between two numeric variables, often over time. It can also compare
multiple groups using different lines.
Syntax:

[Link](x=None, y=None, data=None)

Parameters:
x, y: Numeric input variables. These can be arrays, lists or column names from a DataFrame.
data: DataFrame containing the data.
Example:

import pandas as pd
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link]([Link], df['Age'])
[Link]('Index')
[Link]('Age')
[Link]('Age Line Plot')
[Link]()

Output

Line plot

2. Scatter Plot

Scatter plots are used to visualize the relationship between two numerical variables. They help identify
correlations or patterns. It can draw a two-dimensional graph.
Syntax:

[Link](x=None, y=None, data=None)

Parameters:
x, y: Input data variables that should be numeric.
data (optional): Dataset containing the variables.

Returns: An Axes object with the scatter plot.


Example:

import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link](x=[Link], y='Age', data=df)


[Link]()

Output

Scatter plot

3. Box plot

A box plot is the visual representation of the depicting groups of numerical data with their quartiles against
continuous/categorical data.

It consists of 5 key statistics: Minimum ,First Quartile or 25% , Median (Second Quartile) or 50%, Third
Quartile or 75% and Maximum

Syntax:

[Link](x=None, y=None, hue=None, data=None)

Parameters:

x, y, hue: Variables for plotting long-form data.


data: Dataset to plot. If x and y are absent data is treated as wide-form.

Returns: An Axes object with the box plot.


Example:

import pandas as pd
import [Link] as plt
import seaborn as sns

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 45]}
df = [Link](data)
[Link](y='Age', data=df)
[Link]()

Output

Box plot

4. Violin Plot

A violin plot is similar to a boxplot. It shows several quantitative data across one or more categorical
variables such that those distributions can be compared.
Syntax:

[Link](x=None, y=None, hue=None, data=None)

Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting.

Example:

import pandas as pd
import seaborn as sns
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link](y='Age', data=df)
[Link]()

Output
Violin plot

5. Swarm plot

A swarm plot displays individual data points without overlap along a categorical axis which provides a clear
view of distribution density.
Syntax:

[Link](x=None, y=None, hue=None, data=None)

Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting.

Example:

import pandas as pd
import seaborn as sns
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link](x=[Link], y='Age', data=df)


[Link]()

Output
Swarmplot

6. Bar plot

Barplot represents an estimate of central tendency for a numeric variable with the height of each rectangle
and provides some indication of the uncertainty around that estimate using error bars.
Syntax:

[Link](x=None, y=None, hue=None, data=None)

Parameters :
x, y : Variables or column names for long-form data.
hue : (optional) Column for color encoding.
data : (optional) Dataset to plot.

Returns: Axes object with the bar plot.


Example:

import pandas as pd
import seaborn as sns
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link](x='Name', y='Age', data=df)


[Link]()

Output
Bar plot

7. Point plot

Point plot show point estimates and confidence intervals using scatter glyphs which represents the central
tendency of a numeric variable.
Syntax:

[Link](x=None, y=None, hue=None, data=None)

Parameters:
x, y: Inputs for plotting long-form data.
hue: (optional) column name for color encoding.
data: Dataframe as a Dataset for plotting.

Return: Axes object with the point plot.


Example:

import pandas as pd
import seaborn as sns
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'],'Age': [21, 23, 20, 24]}
df = [Link](data)

[Link](x='Name', y='Age', data=df)


[Link]()

Output
Point Plot

8. Count plot

A Count plot displays the number of occurrences of each category using bars to visualize the distribution of
categorical variables.
Syntax :

[Link](x=None, y=None, hue=None, data=None)

Parameters :
x, y: Inputs for plotting long-form data.
hue: (optional) column name for color encoding.
data: Dataframe as a Dataset for plotting.

Returns: Axes object with the count plot.


Example:

import pandas as pd
import seaborn as sns
import [Link] as plt

data = {'Name': ['ANSH', 'SAHIL', 'ANSH', 'JAYAN', 'ANURAG', 'ANURAG', 'ANURAG', 'SAHIL']}
df = [Link](data)

[Link](x='Name', data=df)
[Link]("Frequency of Names")
[Link]()

Output
Countplot

9. KDE Plot

KDE Plot (Kernel Density Estimate) is used for visualizing the Probability Density of a continuous variable
at different values in a continuous variable. We can also plot a single graph for multiple samples which
helps in more efficient data visualization.
Syntax:

[Link](x=None, *, y=None, vertical=False, palette=None, data=None, **kwargs)

Parameters:
x, y: Vectors or data keys.
vertical: Boolean to plot vertically.
palette: Color palette.
data: Dataframe

Example:

from [Link] import load_iris


import pandas as pd
import seaborn as sns
import [Link] as plt

iris = load_iris()
df = [Link]([Link], columns=iris.feature_names)
df['Species'] = [Link]
df['Species'] = df['Species'].map({ 0: 'Setosa', 1: 'Versicolor', 2: 'Virginica'})

[Link](data=df[df['Species'] == 'Virginica'], x='sepal length (cm)', fill=True, label='Virginica')


[Link]()
[Link]()

Output
KDE plot

How to Customize Seaborn Plots with Python?


Customizing Seaborn plots increases their readability and visual appeal which makes the data insights
clearer and more informative. Here are several ways we can customize our plots in Seaborn:

1. Adding Titles and Axis Labels

Adding descriptive titles and axis labels makes our plots more understandable and informative. Using
Matplotlib's [Link](), [Link]() and [Link]() to set titles and axis labels.

import seaborn as sns


import [Link] as plt

iris = sns.load_dataset('iris')
[Link](x='sepal_length', y='sepal_width', data=iris)

# Add plot title and axis labels


[Link]('Sepal Length vs Sepal Width')
[Link]('Sepal Length (cm)')
[Link]('Sepal Width (cm)')
[Link]()

Output
Adding Titles and Labels

2. Built-in Styles and Grids in Seaborn

Seaborn provides built-in styles that control the background and grid of your plots. These styles improve
readability and can be chosen based on your presentation needs.
Available Styles:
darkgrid – Dark background with light gridlines. Great for clear contrast.
whitegrid – White background with light gridlines. Ideal for statistical plots.
dark – Dark background without gridlines. Clean and modern look.
white – Plain white background without gridlines. Good for simple visuals.
ticks – White background with axis ticks styled sharply. Suitable for publications.

import seaborn as sns


import [Link] as plt

sns.set_style("whitegrid")

[Link](x='species', y='petal_length', data=sns.load_dataset('iris'))


[Link]('Petal Length Distribution by Species')
[Link]()

Output
Representation of Whitegrid in Boxplot

3. Customizing Color Palettes

Seaborn makes it easy to enhance the appearance of plots using color palettes. You can choose from built-in
palettes like "deep", "muted", or "bright" or define your own using sns.color_palette(). Customizing colors
improves clarity and helps match your data’s theme or purpose.
a) Using a Built-in Palette:

sns.set_palette("pastel")

[Link](x='species', y='petal_length', data=sns.load_dataset('iris'))


[Link]('Petal Length Distribution by Species')
[Link]()

Output
Using Built in palette

b) Using a Custom Palette:

custom_colors = ['#FF5733', '#33FFBD', '#335BFF']


sns.set_palette(custom_colors)

[Link](x='species', y='petal_length', data=sns.load_dataset('iris'))


[Link]('Custom Colored Petal Length Distribution')
[Link]()

Using custom palette

4. Adjusting Figure Size and Aspect Ratio


We can adjust the figure size using [Link](figsize=(width,height)) to control the plot's dimensions. This
allows for better customization to fit different presentation or reports.

[Link](figsize=(10, 6))

[Link](x='year', y='passengers', data=sns.load_dataset('flights'))


[Link]('Number of Passengers Over Time')
[Link]()

Output

Adjusting Figure Size and Aspect Ratio

5. Adding Markers to Line Plots

Markers can be added to Seaborn line plots using the marker argument to highlight data points. For
example adding circular markers to the line plot using [Link](x='x', y='y' ,marker='o')

[Link](x='year', y='passengers', data=sns.load_dataset('flights'), marker='o')


[Link]('Number of Passengers Over Time')
[Link]()

Output
Adding marker to lne plot

Visualizing Relationships and Patterns with Seaborn


We’ll see various plots in Seaborn for visualizing relationships, distributions and trends across our dataset.
These visualizations help to find hidden patterns and correlations in datasets with multiple variables.

1. Pair Plots

Pair plots are used explore relationships between several variables by generating scatter plots for every
pair of variables in a dataset along with univariate distributions on the diagonal. This is useful for exploring
datasets with multiple variables and seeing potential correlations.
Syntax:

[Link](data, hue=None)

Parameters:
data: Dataset to plot.
hue: (optional) Categorical variable used for color coding data points.

Returns: An array of Axes objects containing the scatter plot grid and distributions.
Example:

import seaborn as sns


import [Link] as plt

sns.set_style("whitegrid")
custom_palette = sns.color_palette("husl", 8)
sns.set_palette(custom_palette)

data = sns.load_dataset("iris")
[Link](data, hue="species")
[Link]()

Output
Pair Plots

2. Joint Plots

Joint plots combine a scatter plot with the distributions of the individual variables. This allows for a quick
visual representation of how the variables are distributed individually and how they relate to one another.
Syntax:

[Link](x, y, data, kind='scatter')

Parameters:
x, y: Variables to plot.
data: Dataset to plot.
kind: Type of plot to display ('scatter', 'kde', 'reg' etc).

Returns:
An Axes object with the joint plot including scatter plot and distribution plots on the margins.
Example:

import seaborn as sns


import [Link] as plt

data = sns.load_dataset("tips")
[Link](x="total_bill", y="tip", data=data, kind="scatter", color="#008B8B")
[Link]()

Output

Joint plots

This creates a scatter plot between total_bill and tip with histograms of the individual distributions along
the margins. The kind parameter can be set to 'kde' for kernel density estimates or 'reg' for regression plots.

3. Grid Plot

Grid plots in Seaborn are used to create multiple subplots in a grid layout. Using Seaborn's FacetGrid we
can visualize how variables interact across different categories which makesit easier to compare groups or
conditions within our dataset.

Syntax:

g = [Link](data, col='column_name', row='row_name')


[Link]([Link], 'x', 'y')

Parameters:
data: Dataset to plot.
col, row: Variables for the columns and rows of the grid (categorical variables).
[Link]: The plotting function to apply to each facet.

Returns: A FacetGrid object with the grid of plots.

Example: To use FacetGrid, we first need to initialize it with a dataset and specify the variables that will
form the row, column or hue dimensions of the grid. Here is an example using the tips dataset:

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset("tips")

plot=[Link](tips, col="time", row="sex")


[Link]([Link], "total_bill", "tip")
[Link]()

Output

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us Grid
90% Plot AI, ML & Development Kolkata GfG 160
Registered Address:
Regression Plots: Visualizing Linear Relationships
K 061, Tower K, Gulshan Vivante
Corporate Refund Data Science Data Science System Design
Solution on DevOps Programming
Apartment,
Seaborn Sectorthe
simplifies 137,process
Noida, Gautam
of performing
Campusand visualizing
Courses regressions
CS Core specifically
Languages linear regressions
Buddh Nagar, Uttar Pradesh, 201305
which is important for identifying relationships
Training between variables, detectingDevOps
Subjects trends& and making predictions.
Program GATE Cloud
It supports two primary functions for regression visualization:
School GATE

regplot(): This function plots a scatter plot along with a linear regression Trending
Subjects
model fit.
Software and Technologies
lmplot(): This function also plots linear models but providesTools
more flexibility in handling multiple facets
and datasets.

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Example: Let’s use a simple dataset to visualize a linear regression between two variables: x (independent
variable) and y (dependent variable).

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')

[Link](x='total_bill', y='tip', data=tips, scatter_kws={'s':10}, line_kws={'color':'red'})


[Link]()

Output:

Regression Plots

As we explore Seaborn functions and techniques we can create clear, customized and insightful
visualizations that helps us to understand our data better.

Suggested Quiz 5 Questions

Which of the following Seaborn plots is used to visualize the relationship between two numerical variables?

A Bar plot

B Scatter plot

C Box plot

D Heatmap

View Explanation 1/5 < Previous Next >


Comment
K kumar… Follow 19

Article Tags: Technical Scripter Data Visualization AI-ML-DS Technical Scripter 2020 +4 More
Search...
Tutorials
Practice V
Jobs
a Visualization Tutorial With Python Types Matplotlib Altair Plotly Computer Vision OpenCV Computer Graphics Tutorial Deep Learn

Data Visualisation in Python using Matplotlib and Seaborn


Last Updated : 9 Nov, 2022

It may sometimes seem easier to go through a set of data points and build insights from it but usually
this process may not yield good results. There could be a lot of things left undiscovered as a result of
this process. Additionally, most of the data sets used in real life are too big to do any analysis
manually. This is essentially where data visualization steps in.
Data visualization is an easier way of presenting the data, however complex it is, to analyze trends
and relationships amongst variables with the help of pictorial representation.
The following are the advantages of Data Visualization
Easier representation of compels data
Highlights good and bad performing areas
Explores relationship between data points
Identifies data patterns even for larger data points

While building visualization, it is always a good practice to keep some below mentioned points in
mind
Ensure appropriate usage of shapes, colors, and size while building visualization
Plots/graphs using a co-ordinate system are more pronounced
Knowledge of suitable plot with respect to the data types brings more clarity to the information
Usage of labels, titles, legends and pointers passes seamless information the wider audience

Python Libraries
There are a lot of python libraries which could be used to build visualization like matplotlib, vispy,
bokeh, seaborn, pygal, folium, plotly, cufflinks, and networkx. Of the many, matplotlib and seaborn
seems to be very widely used for basic to intermediate level of visualizations.

Matplotlib

It is an amazing visualization library in Python for 2D plots of arrays, It is a multi-platform data


visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was
introduced by John Hunter in the year 2002. Let's try to understand some of the benefits and features
of matplotlib
It's fast, efficient as it is based on numpy and also easier to build
Has undergone a lot of improvements from the open source community since inception and hence
a better library having advanced features as well
Well maintained visualization output with high quality graphics draws a lot of users to it
Basic as well as advanced charts could be very easily built
From the users/developers point of view, since it has a large community support, resolving issues
and debugging becomes much easier

Seaborn
Conceptualized and built originally at the Stanford University, this library sits on top of matplotlib. In
a sense, it has some flavors of matplotlib while from the visualization point, it is much better than
matplotlib and has added features as well. Below are its advantages
Built-in themes aid better visualization
Statistical functions aiding better data insights
Better aesthetics and built-in plots
Helpful documentation with effective examples

Nature of Visualization
Depending on the number of variables used for plotting the visualization and the type of variables,
there could be different types of charts which we could use to understand the relationship. Based on
the count of variables, we could have
Univariate plot(involves only one variable)
Bivariate plot(more than one variable in required)

A Univariate plot could be for a continuous variable to understand the spread and distribution of the
variable while for a discrete variable it could tell us the count
Similarly, a Bivariate plot for continuous variable could display essential statistic like correlation, for a
continuous versus discrete variable could lead us to very important conclusions like understanding
data distribution across different levels of a categorical variable. A bivariate plot between two
discrete variables could also be developed.

Box plot
A boxplot, also known as a box and whisker plot, the box and the whisker are clearly displayed in the
below image. It is a very good visual representation when it comes to measuring the data
distribution. Clearly plots the median values, outliers and the quartiles. Understanding data
distribution is another important factor which leads to better model building. If data has outliers, box
plot is a recommended way to identify them and take necessary actions.

Syntax: [Link](x=None, y=None, hue=None, data=None, order=None,


hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8,
dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None, **kwargs)

Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form.
color: Color for all of the elements.

Returns: It returns the Axes object with the plot drawn onto it.

The box and whiskers chart shows how data is spread out. Five pieces of information are generally
included in the chart
1. The minimum is shown at the far left of the chart, at the end of the left ‘whisker’
2. First quartile, Q1, is the far left of the box (left whisker)
3. The median is shown as a line in the center of the box
4. Third quartile, Q3, shown at the far right of the box (right whisker)
5. The maximum is at the far right of the box
As could be seen in the below representations and charts, a box plot could be plotted for one or
more than one variable providing very good insights to our data.
Representation of box plot.

Box plot representing multi-variate categorical variables

Box plot representing multi-variate categorical variables

# import required modules


import matplotlib as plt
import seaborn as sns

# Box plot and violin plot for Outcome vs BloodPressure


_, axes = [Link](1, 2, sharey=True, figsize=(10, 4))

# box plot illustration


[Link](x='Outcome', y='BloodPressure', data=diabetes, ax=axes[0])

# violin plot illustration


[Link](x='Outcome', y='BloodPressure', data=diabetes, ax=axes[1])

Output for Box Plot and Violin Plot

# Box plot for all the numerical variables


[Link](rc={'[Link]': (16, 5)})

# multiple box plot illustration


[Link](data=diabetes.select_dtypes(include='number'))
Output Multiple Box PLot

Scatter Plot
Scatter plots or scatter graphs is a bivariate plot having greater resemblance to line graphs in the
way they are built. A line graph uses a line on an X-Y axis to plot a continuous function, while a
scatter plot relies on dots to represent individual pieces of data. These plots are very useful to see if
two variables are correlated. Scatter plot could be 2 dimensional or 3 dimensional.

Syntax: [Link](x=None, y=None, hue=None, style=None, size=None, data=None,


palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None,
size_norm=None, markers=True, style_order=None, x_bins=None, y_bins=None, units=None,
estimator=None, ci=95, n_boot=1000, alpha=’auto’, x_jitter=None, y_jitter=None, legend=’brief’,
ax=None, **kwargs)
Parameters:
x, y: Input data variables that should be numeric.

data: Dataframe where each column is a variable and each row is an observation.

size: Grouping variable that will produce points with different sizes.

style: Grouping variable that will produce points with different markers.

palette: Grouping variable that will produce points with different markers.

markers: Object determining how to draw the markers for different levels.

alpha: Proportional opacity of the points.

Returns: This method returns the Axes object with the plot drawn onto it.

Advantages of a scatter plot

Displays correlation between variables


Suitable for large data sets
Easier to find data clusters
Better representation of each data point

# import module
import [Link] as plt
# scatter plot illustration
[Link](diabetes['DiabetesPedigreeFunction'], diabetes['BMI'])

Output 2D Scattered Plot

# import required modules


from mpl_toolkits.mplot3d import Axes3D

# assign axis values


x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [5, 6, 2, 3, 13, 4, 1, 2, 4, 8]
z = [2, 3, 3, 3, 5, 7, 9, 11, 9, 10]

# adjust size of plot


[Link](rc={'[Link]': (8, 5)})
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
[Link](x, y, z, c='r', marker='o')

# assign labels
ax.set_xlabel('X Label'), ax.set_ylabel('Y Label'), ax.set_zlabel('Z Label')

# display illustration
[Link]()

Output 3D Scattered Plot

Histogram
Histograms display counts of data and are hence similar to a bar chart. A histogram plot can also tell
us how close a data distribution is to a normal curve. While working out statistical method, it is very
important that we have a data which is normally or close to a normal distribution. However,
histograms are univariate in nature and bar charts bivariate.
A bar graph charts actual counts against categories e.g. height of the bar indicates the number of
items in that category whereas a histogram displays the same categorical variables in bins.
Bins are integral part while building a histogram they control the data points which are within a
range. As a widely accepted choice we usually limit bin to a size of 5-20, however this is totally
governed by the data points which is present.

# illustrate histogram
features = ['BloodPressure', 'SkinThickness']
diabetes[features].hist(figsize=(10, 4))

Output Histogram

Countplot
A countplot is a plot between a categorical and a continuous variable. The continuous variable in this
case being the number of times the categorical is present or simply the frequency. In a sense, count
plot can be said to be closely linked to a histogram or a bar graph.

Syntax : [Link](x=None, y=None, hue=None, data=None, order=None,


hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True,
ax=None, **kwargs)
Parameters : This method is accepting the following parameters that are described below:

x, y: This parameter take names of variables in data or vector data, optional, Inputs for
plotting long-form data.
hue : (optional) This parameter take column name for colour encoding.
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting.
If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-
form.
order, hue_order : (optional) This parameter take lists of strings. Order to plot the
categorical levels in, otherwise the levels are inferred from the data objects.
orient : (optional)This parameter take “v” | “h”, Orientation of the plot (vertical or horizontal).
This is usually inferred from the dtype of the input variables but can be used to specify when
the “categorical” variable is a numeric or when plotting wide-form data.
color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed
for a gradient palette.
palette : (optional) This parameter take palette name, list, or dict, Colors to use for the
different levels of the hue variable. Should be something that can be interpreted by
color_palette(), or a dictionary mapping hue levels to matplotlib colors.
saturation : (optional) This parameter take float value, Proportion of the original saturation
to draw colors at. Large patches often look better with slightly desaturated colors, but set
this to 1 if you want the plot colors to perfectly match the input color spec.
dodge : (optional) This parameter take bool value, When hue nesting is used, whether
elements should be shifted along the categorical axis.
ax : (optional) This parameter take matplotlib Axes, Axes object to draw the plot onto,
otherwise uses the current Axes.
kwargs : This parameter take key, value mappings, Other keyword arguments are passed
through to [Link]().

Returns: Returns the Axes object with the plot drawn onto it.

It simply shows the number of occurrences of an item based on a certain type of [Link] python,
we can create a count plot using the seaborn library. Seaborn is a module in Python that is built on
top of matplotlib and used for visually appealing statistical plots.

# import required module


import seaborn as sns

# assign required values


_, axes = [Link](nrows=1, ncols=2, figsize=(12, 4))

# illustrate count plots


[Link](x='Outcome', data=diabetes, ax=axes[0])
[Link](x='BloodPressure', data=diabetes, ax=axes[1])

Output Countplot

Correlation plot
Correlation plot is a multi-variate analysis which comes very handy to have a look at relationship
with data points. Scatter plots helps to understand the affect of one variable over the other.
Correlation could be defined as the affect which one variable has over the other.
Correlation could be calculated between two variables or it could be one versus many correlations as
well which we could see the below plot. Correlation could be positive, negative or neutral and the
mathematical range of correlations is from -1 to 1. Understanding the correlation could have a very
significant effect on the model building stage and also understanding the model outputs.

# Finding and plotting the correlation for


# the independent variables

# import required module


import seaborn as sns

# adjust plot
[Link](rc={'[Link]': (14, 5)})

# assign data
ind_var = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM',
'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']

# illustrate heat map.


[Link](diabetes.select_dtypes(include='number').corr(),
cmap=sns.cubehelix_palette(20, light=0.95, dark=0.15))

Output Correlation Plot

Heat Maps
Heat map is a multi-variate data representation. The color intensity in a heat map displays becomes
an important factor to understand the affect of data points. Heat maps are easier to understand and
easier to explain as well. When it comes to data analysis using visualization, its very important that
the desired message gets conveyed with the help of plots.

Syntax:

[Link](data, *, vmin=None, vmax=None, cmap=None, center=None, robust=False,


annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True,
cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto',
mask=None, ax=None, **kwargs)

Parameters : This method is accepting the following parameters that are described below:

x, y: This parameter take names of variables in data or vector data, optional, Inputs for
plotting long-form data.
hue : (optional) This parameter take column name for colour encoding.
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting.
If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-
form.
color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed
for a gradient palette.
palette : (optional) This parameter take palette name, list, or dict, Colors to use for the
different levels of the hue variable. Should be something that can be interpreted by
color_palette(), or a dictionary mapping hue levels to matplotlib colors.
ax : (optional) This parameter take matplotlib Axes, Axes object to draw the plot onto,
otherwise uses the current Axes.
kwargs : This parameter take key, value mappings, Other keyword arguments are passed
through to [Link]().

Returns: Returns the Axes object with the plot drawn onto it.
# import required module
import seaborn as sns
import numpy as np

# assign data
data = [Link](50, 20)

# illustrate heat map


ax = [Link](data, xticklabels=2, yticklabels=False)

Output Heat Map

Pie Chart
Pie chart is a univariate analysis and are typically used to show percentage or proportional data. The
percentage distribution of each class in a variable is provided next to the corresponding slice of the
pie. The python libraries which could be used to build a pie chart is matplotlib and seaborn.

Syntax: [Link](data, explode=None, labels=None, colors=None, autopct=None,


shadow=False)

Parameters:
data represents the array of data values to be plotted, the fractional area of each slice is
represented by data/sum(data). If sum(data)<1, then the data values returns the fractional area
directly, thus resulting pie will have empty wedge of size 1-sum(data).
labels is a list of sequence of strings which sets the label of each wedge.
color attribute is used to provide color to the wedges.
autopct is a string used to label the wedge with their numerical value.
shadow is used to create shadow of wedge.

Below are the advantages of a pie chart


Easier visual summarization of large data points
Effect and size of different classes can be easily understood
Percentage points are used to represent the classes in the data points

# import required module


import [Link] as plt

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]

# Creating plot
fig = [Link](figsize=(10, 7))
[Link](data, labels=cars)
# Show plot
[Link]()

Output Pie Chart

# Import required module


import [Link] as plt
import numpy as np

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]

# Creating explode data


explode = (0.1, 0.0, 0.2, 0.3, 0.0, 0.0)

# Creating color parameters


colors = ("orange", "cyan", "brown", "grey", "indigo", "beige")

# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}

# Creating autocpt arguments


def func(pct, allvalues):
absolute = int(pct / 100.*[Link](allvalues))
return "{:.1f}%\n({:d} g)".format(pct, absolute)

# Creating plot
fig, ax = [Link](figsize=(10, 7))
wedges, texts, autotexts = [Link](data, autopct=lambda pct: func(pct, data), explode=explode, labels=cars,
shadow=True, colors=colors, startangle=90, wedgeprops=wp,
textprops=dict(color="magenta"))

# Adding legend
[Link](wedges, cars, title="Cars", loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
[Link](autotexts, size=8, weight="bold")
ax.set_title("Customizing pie chart")

# Show plot
[Link]()

Output

Error Bars
Error bars could be defined as a line through a point on a graph, parallel to one of the axes, which
represents the uncertainty or error of the corresponding coordinate of the point. These types of plots
are very handy to understand and analyze the deviations from the target. Once errors are identified, it
could easily lead to deeper analysis of the factors causing them.
Deviation of data points from the threshold could be easily captured
Easily captures deviations from a larger set of data points
It defines the underlying data

# Import required module


import [Link] as plt
import numpy as np

# Assign axes
x = [Link](0,5.5,10)
y = 10*[Link](-x)

# Assign errors regarding each axis


xerr = [Link].random_sample(10)
yerr = [Link].random_sample(10)

# Adjust plot
fig, ax = [Link]()
[Link](x, y, xerr=xerr, yerr=yerr, fmt='-o')

# Assign labels
ax.set_xlabel('x-axis'), ax.set_ylabel('y-axis')
ax.set_title('Line plot with error bars')
# Illustrate error bars
[Link]()

Output Error Plot

Comment D digitar… Follow 2

Article Tags: Data Visualization AI-ML-DS Python-matplotlib Python-Seaborn +2 More

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python for Machine Learning Machine Learning with R Machine Learning Algorithms EDA Math for Machine Learning Machine Learning Inte

Visualising ML DataSet Through Seaborn Plots and Matplotlib


Last Updated : 8 Dec, 2021

Working on data can sometimes be a bit boring. Transforming a raw data into an understandable
format is one of the most essential part of the whole process, then why to just stick around on
numbers, when we can visualize our data into mind-blowing graphs which are up for grabs in python.
This article will focus on exploring plots which could make your preprocessing journey, intriguing.
Seaborn and Matplotlib provide us with numerous alluring graphs through which one can easily
analyze weak points, explore data with a deeper understanding and eventually end up getting a
great insight into data and gaining the highest accuracy after training it through different algorithms.
Let's Have A Glance Through Our Dataset : The Dataset (36 rows) contains 6 Features And 2
Classes (Survived = 1, Not Survived = 0 ) Based on which we'll plot certain graphs. Link of the
dataset - Click Here To Get Complete Dataset
1. KDE PLOT : Okay So after having a glance through the dataset we can have a question. Which
Age Group Has Maximum No. Of People? To answer this question we need visuals where Our KDE
Plot comes into the picture, it is simply a density plot. So let's start with importing required libraries
and use its functions to plot the graph.

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# KDE plot
[Link](dataset["Age"], color = "green", Loading Playground...
shade = True)
[Link]()
[Link]()

Output :

2. So now we have a clear picture of how the Count Of People vs Age-Group is distributed, here we
can see that the age group 20-40 has maximum count so let's check it.

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# Checking the count of Age Group 20-40 Loading Playground...


[Link][(dataset["Age"] >= 20) & (dataset["Age"] <= 40)].count()

Output :

26

3. Digging deeper into visuals, to know about the variation in Fair Vs Age, what is the relation
between them, let's have a look using a different kind of kdeplot simply now there'll be bivariate
densities, we will just add the Y Variable(Fair).

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

[Link](dataset["Age"], dataset["Fare"], shade = True)


Loading Playground...
[Link]()
[Link]()

Output :

4. After Studying this plot a bit, we see that the intensity of the color is maximum between the age
group 20-30 and precisely these have a fair between 100-200, let's check it

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# Checking The Variation Between Fare And Age


[Link][((dataset["Fare"] >= 100) & Loading Playground...
(dataset["Fare"]<=200)) &
((dataset["Age"]>=20) &
dataset["Age"]<=40)].count()

Output :
16

5. We can also add a histogram to kdeplot just by using distplot() module of seaborn :

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# Histogram+Density Plot
[Link](dataset["Age"], color = "green") Loading Playground...
[Link]()
[Link]()

Output :

6. Well. If one wants to know about the Male Vs Female Proportion, We can plot the same in KDE
itself :

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# Adding Two Plots In One


[Link](dataset[[Link] == 'Female']['Age'],
color = "blue") Loading Playground...
[Link](dataset[[Link] == 'Male']['Age'],
color = "orange", shade = True)
[Link]()
[Link]()

Output :
7. As We can see from the plot there is an increase in the count after Age 12 till Age 40, let's check
for the same

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# showing that there are more Male's Between Age Of 12-40


[Link][((dataset["Age"] >= 12) &
(dataset["Age"] <= 40)) & Loading Playground...
(dataset["Gender"] == "Male")].count()
[Link][((dataset["Age"] >= 12) &
(dataset["Age"] <= 40)) &
(dataset["Gender"] == "Female")].count()

Output :

17
15

8. VIOLIN PLOT : We have talked much about the features, now let's talk about Survival Rate
Dependency On Features. For This, We will use a classic Violin Plot, as the name suggests it portrays
the same visuals as that of the musical waves of a violin. Basically A Violin Plot is used to visualize
the distribution of the data and its probability density.
What is the Relation Between Survival Rate And Age? Let's Visually Analyze It :

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

[Link](x = 'Survived', y = 'Age', data = dataset,


Loading Playground...
palette = {0 : "yellow", 1 : "orange"});
[Link]()
[Link]()

Output :
Explanation : The white dot we see in the plot is median and thick black bar in the center represents
the interquartile
[Link] thin black line extended from it represents the upper (max) and lower (min) adjacent
values in the data.
A Quick glance show's us that between Age[10-20] The Survival Rate is A bit higher(Survived==1).
9. Let's plot one more for the Survival Rate Vs Gender and Age

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

[Link](x = "Gender", y = "Age", hue = "Survived",


data = dataset, Loading Playground...
palette = {0 : "yellow", 1 : "orange"})
[Link]()
[Link]()

Here an additional attribute is hue, which refers to the binary value for Survived.
Output :

10. CATPLOT : In simple terms, catplot shows frequencies (or optionally fractions or percents) of the
categories of one, two, or three categorical variables.

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# Plot a nested barplot to show survival for Siblings and Gender


g = [Link](x = "Siblings", y = "Survived", Loading
hue = "Gender",
Playground...
data = dataset,
height = 6, kind = "bar", palette = "muted")
[Link](lef t= True)
g.set_ylabels("Survival Probability")
[Link]()

Here [Link] is used to remove the top and right spines from the plot, let's have a look at it.
Output :

Here We get a clear picture of Gender Wise Survival Probability w.r.t No. Of Siblings.
11. Now, in The Dataset We See There Are Three Categories in Ticket, Which is based on Fare, Let's
Find About It (Referring This Plot I Added A Category Column For Tickets)

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

# Based On Fare There Are 3 Types Of Tickets


Loading Playground...
[Link](x = "PassType", y = "Fare", data = dataset)
[Link]()
[Link]()

Output :
Using This we concluded that categories should be defined for tickets
12. Relation of the same with Survival Rate :

# importing the modules and dataset


import pandas as pd
import [Link] as plt
import seaborn as sns
dataset = pd.read_csv("[Link]")

[Link](x="PassType", y="Fare", hue="Survived",kind="swarm",data=dataset)


Loading Playground...
[Link]()
[Link]()

Output :

From this, we get a clear insight for Survival Rate Vs Fare w.r.t Category of Tickets.

Comment A abskin… Follow 1

Article Tags: Machine Learning AI-ML-DS Python-matplotlib python +2 More


Company Explore Tutorials Courses Offline Preparation
About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
DSA Practice Problems C C++ Java Python JavaScript Data Science Machine Learning Courses

Binomial Distribution in NumPy


Last Updated : 5 Dec, 2025

The Binomial Distribution models the number of successes in a fixed number of independent trials
where each trial has only two outcomes: success or failure. In NumPy, we use the
[Link]() method to generate values that follow this distribution. It is commonly
used in coin flips, defect detection, surveys, and probability experiments.

Example: Here, we generate one binomial random value using 10 trials and a 0.5 probability of
success.

import numpy as np
x = [Link](n=10, p=0.5)
print(x)

Output

Explanation: [Link](n=10, p=0.5) simulates 10 yes/no events and returns how many
times success occurred.

Syntax
[Link](n, p, size=None)

Parameters:
n: Number of trials
p: Probability of success in each trial
size: Shape of output array

Examples
Example 1: In this example, we generate 5 binomial random numbers using 10 trials and 0.5
probability.

import numpy as np
arr = [Link](n=10, p=0.5, size=5)
print(arr)

Output
[7 2 5 4 7]

Explanation: [Link](..., size=5) returns an array of 5 simulated outcomes.

Example 2: Here, we simulate 8 trials with different success probability (p = 0.3).

import numpy as np
x = [Link](8, 0.3, size=4)
print(x)

Output

[4 4 4 4]

Explanation: [Link](8, 0.3) generates values where success occurs with 30%
probability.

Example 3: In this example, we generate a 2×3 matrix of binomial outcomes.

import numpy as np
m = [Link](12, 0.6, size=(2, 3))
print(m)

Output

[[8 7 9]
[6 8 5]]

Explanation: size=(2,3) creates a 2D array where each entry is a binomial random value.

Visualizing the Binomial Distribution


Visualizing the generated numbers helps in understanding their behavior. Below is an example of
plotting a histogram of random numbers generated using [Link].

import numpy as np
import [Link] as plt
from [Link] import binom

n = 10
p = 0.5
size = 1000

data = [Link](n, p, size)

[Link](data, bins=[Link](-0.5, n+1.5, 1), density=True, edgecolor='black', alpha=0.7,


label='Histogram')

x = [Link](0, n+1)
pmf = [Link](x, n, p)

[Link](x, pmf, color='red', label='Theoretical PMF')


[Link](x, 0, pmf, colors='red', linestyles='dashed')

[Link]("Binomial Distribution (n=10, p=0.5)")


[Link]("Number of Successes")
[Link]("Probability")
[Link]()
[Link](True)
[Link]()
Output

Binomial Distribution Plot

Explanation:
[Link](n, p, size) generates 1000 simulated outcomes.
[Link](..., density=True) shows the frequency distribution of these values.
[Link](x, n, p) computes the theoretical probability for each possible success count.
Red dots and dashed lines show the true Binomial PMF for comparison.

Comment A ayushi… Follow 8

Article Tags: Numpy python


Company Explore Tutorials Courses Offline Preparation
About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

Numpy [Link]() - Python


Last Updated : 18 Nov, 2025

The [Link]() function is used to change the size of an existing NumPy array. It modifies the
array permanently and adjusts its shape to the new dimensions. If the new shape requires more
elements than available, NumPy repeats the array elements. If less space is required, elements are
truncated.

Example 1: This example resizes a 1D array of 6 elements into a 2×3 array. No values need
repetition or truncation.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
[Link]((2, 3))
print(arr)
Loading Playground...

Output

[[1 2 3]
[4 5 6]]

Syntax

[Link](a, new_shape)

Parameters:
a: Input array to be resized.
new_shape: Target shape (int or tuple).
refcheck(optional): If True, checks whether the array is referenced elsewhere before resizing.

Example 2: This example resizes a 6-element array into a 3×4 shape (12 elements needed). NumPy
repeats the array elements to fill the new size.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
[Link]((3, 4))
print(arr)
Loading Playground...

Output
[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]

Example 3: This example resizes an array into a 2×2 shape. Since fewer elements are required, the
extra values are removed.

import numpy as np
arr = [Link]([10, 20, 30, 40, 50])
[Link]((2, 2))
print(arr)
Loading Playground...

Output

[[10 20]
[30 40]]

Comment J jitende… Follow 5

Article Tags: Python Python-numpy

Company Explore Tutorials Courses Offline Preparation


About Us POTD Programming ML and Data Centers Corner
Corporate & Communications Address: Legal Practice Languages Science Noida Interview
Privacy Problems DSA DSA and Bengaluru Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Pune Aptitude
Pradesh (201305) Careers Blogs Technology Web Hyderabad Puzzles
Contact Us 90% AI, ML & Development Kolkata GfG 160
Registered Address:
Corporate Refund Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution on DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects Trending
Software and Technologies
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like