0% found this document useful (0 votes)
12 views143 pages

Numpy 2

The document provides an overview of various statistical distributions in NumPy, specifically the Exponential and Chi-Square distributions, including how to generate random values and visualize them. It also discusses vectorization in NumPy, highlighting its advantages in performance and code simplicity through practical examples. The document emphasizes the efficiency of vectorized operations compared to traditional loops in Python.

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)
12 views143 pages

Numpy 2

The document provides an overview of various statistical distributions in NumPy, specifically the Exponential and Chi-Square distributions, including how to generate random values and visualize them. It also discusses vectorization in NumPy, highlighting its advantages in performance and code simplicity through practical examples. The document emphasizes the efficiency of vectorized operations compared to traditional loops in Python.

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 Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice

Exponential Distribution in NumPy


Last Updated : 10 Dec, 2025

The Exponential Distribution is a continuous probability distribution that describes the time between
two events in a Poisson process, where events occur independently and at a constant average rate.
NumPy provides a simple method to generate such random values: [Link]().

Example: This example shows how to generate one exponential random value using the default
parameters.

import numpy as np
x = [Link]()
print(x)

Loading Playground...

Output

0.5339358426948082

Explanation:

[Link]() generates one value following the exponential distribution.


Since no parameters are passed, it uses scale = 1 by default.

Syntax

[Link](scale=1.0, size=None)

Parameters:

scale: Inverse of the event rate (β = 1/λ).


size: Shape of output array.

Examples
Example 1: This example generates one exponential random value using a custom scale.

import numpy as np
x = [Link](scale=2)
print(x)

Loading Playground...

Output
0.8177243559186411

Explanation:
scale=2 values will be more spread out.
x holds a single exponential random number.
Larger scale values make the distribution longer and wider.

Example 2: This example generates five random numbers from the exponential distribution.

import numpy as np
arr = [Link](scale=1.5, size=5)
print(arr)

Loading Playground...

Output

[2.14106221 1.93254045 0.03957526 0.58763751 1.12814399]

Explanation
scale=1.5 moderate spread.
size=5 returns 5 values.
arr stores the array like [0.21, 1.33, 0.94, ...].

Visualizing the Exponential 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
import seaborn as sns

s = 2 # scale
n = 800 # number of points

data = [Link](scale=s, size=n)


[Link](data, bins=30, kde=True, edgecolor='black')
Loading Playground...
[Link](f"Exponential Distribution (Scale={s})")
[Link]("Value")
[Link]("Frequency")
[Link](True)
[Link]()

Output
Exponenetial Distribution Plot

Explanation:
s = 2 sets the spread of the distribution.
n = 800 creates enough data points for a smooth histogram.
[Link]() shows: Bars -> simulated data and Curve (kde) -> smooth theoretical shape
The graph shows high frequency near 0 and a long decreasing tail, which is typical of exponential
distributions.

Comment J jitende… Follow 1

Article Tags: Python Python-numpy Python numpy-Random

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 AI, ML & Development Kolkata GfG 160
Registered Address:
Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Corporate 90% DevOps Programming
Apartment, Sector 137, Noida, Gautam Solution Refund CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Campus on Subjects DevOps &
Training Courses GATE Cloud
Program 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

Chi-Square Distribution in NumPy


Last Updated : 10 Dec, 2025

The Chi-Square Distribution appears when you add up the squares of independent standard normal
random variables. It is widely used in hypothesis testing, goodness-of-fit tests, variance testing, and
statistical modeling. In NumPy, we generate Chi-Square values using [Link]().

Example: Here, we generate one Chi-Square random value using df = 2 (degrees of freedom).

import numpy as np
x = [Link](df=2)
print(x)

Loading Playground...

Output

0.3396810372458067

Explanation: [Link](df=2) generates one value formed by summing the squares of 2


standard normal variables.

Syntax

[Link](df, size=None)

Parameters:

df: Degrees of freedom (controls the shape of the curve)


size: Shape of output array

Examples
Example 1: In this example, we generate 5 Chi-Square random values with df = 2.

import numpy as np
arr = [Link](df=2, size=5)
print(arr)

Loading Playground...

Output

[0.9664276 0.9718178 0.05315296 5.76413224 0.17793754]

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


Example 2: Here, we generate Chi-Square values with a higher degree of freedom (df = 5).

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

Loading Playground...

Output

[5.5554776 8.39987081 1.96062558 1.15995049]

Explanation: [Link](5) produces values based on 5 summed squares, giving a wider


and more symmetric shape.

Example 3: In this example, we generate a 2×3 matrix of Chi-Square random values.

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

Loading Playground...

Output

[[0.04478657 4.99709829 0.51742473]


[0.87978466 1.96904351 3.51846182]]

Explanation: size=(2,3) creates a matrix where each element is a Chi-Square-distributed value.

Visualizing the Chi-Square Distribution


Visualizing the generated numbers helps in understanding how the Chi-Square curve behaves for
different degrees of freedom.

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

df = 2
size = 1000

data = [Link](df, size)


[Link](data, bins=30, density=True, edgecolor='black', alpha=0.7, label='Histogram')

x = [Link](0, max(data), 200) Loading Playground...


pdf = [Link](x, df)
[Link](x, pdf, color='red', label='Theoretical PDF')

[Link](f"Chi-Square Distribution (df={df})")


[Link]("Value")
[Link]("Density")
[Link]()
[Link](True)
[Link]()
Output

Chi-square Distribution Plot

Explanation:
[Link](df, size) simulates 1000 Chi-Square values.
[Link](..., density=True) displays their frequency.
[Link](x, df) computes the true theoretical curve.
The red line shows how the actual Chi-Square distribution should look for df = 2.
Chi-Square distributions are right-skewed, especially at lower degrees of freedom.

Comment J jitende… Follow

Article Tags: Python Python-numpy Python numpy-Random

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 Development Kolkata GfG 160
Registered Address: Corporate 90% AI, ML & Data Science System Design
Solution Refund Data Science Programming
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam Campus on DevOps Languages
Buddh Nagar, Uttar Pradesh, 201305 Training Courses CS Core DevOps &
Program Subjects Cloud
GATE GATE
School Trending
Subjects Technologies
Software and
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

Vectorization in NumPy with Practical Examples


Last Updated : 10 Dec, 2025

Vectorization in NumPy refers to applying operations on entire arrays without using explicit loops.
These operations are internally optimized using fast C/C++ implementations, making numerical
computations more efficient and easier to write.

Why Vectorization Matters?

Vectorization is important because it:

Improves Performance: Eliminates Python-level loops and leverages fast low-level


implementations.
Produces Cleaner Code: Fewer lines, easier to maintain.
Scales Better: Can efficiently handle large scientific data and machine learning workloads.

Examples of Vectorization

Example 1: Add a number to each element

Performs element-wise addition across the entire array without using loops, making the operation
fast and efficient.

import numpy as np

a1 = [Link]([2, 4, 6, 8, 10])
num = 2
res = a1 + num
print(res) Loading Playground...

Output

[ 4 6 8 10 12]

Example 2: Adding Two Arrays Element-wise

Performs element-wise addition of two NumPy arrays.

import numpy as np

a1 = [Link]([1, 2, 3])
a2 = [Link]([4, 5, 6])
res = a1 + a2
print(res) Loading Playground...

Output

[5 7 9]

Example 3: Element-Wise Scalar Multiplication

Multiplies each element in the array by a constant value using fast vectorized array operations
instead of loops.

import numpy as np
a1 = [Link]([1, 2, 3, 4])
res = a1 * 2
print(res)
Loading Playground...

Output

[2 4 6 8]

Example 4: Logical Operations on Arrays

Logical operations such as comparisons can be applied directly to arrays.

import numpy as np
a1 = [Link]([10, 20, 30])
res = a1 > 15
print(res)
Loading Playground...

Output

[False True True]

Explanation: Performs element-wise comparison, returning a boolean array indicating which


elements are greater than 15.

Example 5: Matrix Operations Using Vectorization

NumPy supports vectorized matrix operations like dot products and matrix multiplications using
functions such as [Link] and @.

import numpy as np
a1= [Link]([[1, 2], [3, 4]])
a2 = [Link]([[5, 6], [7, 8]])
res = [Link](a1, a2)
print(res) Loading Playground...

Output

[[19 22]
[43 50]]

Explanation: Performs matrix multiplication (dot product) between a1 and a2.

Example 6: Applying Custom Functions Using [Link]()

[Link] applies a custom function element-wise to a NumPy array, e.g., computing x² + 2x + 1


for each element efficiently.

import numpy as np

a1 = [Link]([1, 2, 3, 4])
vec = [Link](lambda x: x**2 + 2*x + 1)
res = vec(a1)
print(res) Loading Playground...

Output

[ 4 9 16 25]

Explanation: Performs the operation x**2+2*x+1 element-wise on the array a1 using NumPy’s
vectorized arithmetic.

Example 7: Vectorized Aggregation Operations

Operations like sum, mean, max are optimized with much faster than the traditional Python approach
of looping through elements.

import numpy as np
a1 = [Link]([1, 2, 3])
r1 = [Link]()
r2= [Link]()
print(r1)
print(r2) Loading Playground...
Output

6
2.0

Explanation: Calculates the sum (r1) and mean (r2) of all elements in the array a1 using NumPy’s
vectorized aggregation functions.

Performance Comparison: Loop vs. Vectorization


When working with large datasets, performance matters. In Pandas and NumPy, vectorization is
almost always faster than writing manual Python loops. This is because vectorized operations are
executed in optimized C code internally, while Python loops run line-by-line in Python (much
slower).

Example: We will create a large NumPy array and apply the same operation (multiply each element
by 2) using both:

For Loop (Python-level)


Vectorized Operation (NumPy-level)

import numpy as np
import time

arr = [Link](1_000_000)

# Loop
t1 = [Link]()
loop_res = [x * 2 for x in arr]
t2 = [Link]()
Loading Playground...
# Vectorized
t3 = [Link]()
vec_res = arr * 2
t4 = [Link]()

print("Loop Time:", t2 - t1)


print("Vectorized Time:", t4 - t3)

Output

Loop Time: 0.14799761772155762


Vectorized Time: 0.04310011863708496

Explanation:
arr = [Link](1_000_000): Creates a NumPy array with 1 million numbers.
Loop method: [x * 2 for x in arr] processes each element one-by-one in Python, which is slow
and t2 - t1 measures how long the loop took.
Vectorized method: arr * 2 uses fast optimized C-level operations inside NumPy and t4 - t3
measures how fast vectorization is.
Vectorization is significantly faster because operations happen in optimized low-level code instead of
Python's slow element-by-element loop.

Related Articles:

NumPy Tutorial - Python Library


Create your own universal function in NumPy

Comment V vipulp… Follow 3

Article Tags: Numpy 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


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

NumPy Array Broadcasting


Last Updated : 5 Dec, 2025

Broadcasting in NumPy allows us to perform arithmetic operations on arrays of different shapes


without reshaping them. It automatically adjusts the smaller array to match the larger array's shape
by replicating its values along the necessary dimensions. This makes element-wise operations more
efficient by reducing memory usage and eliminating the need for loops.
Lets see an example:

import numpy as np

a = [Link]([[1, 2, 3], [4, 5, 6]])


x = 10
print(a + x)
Loading Playground...

Output

[[11 12 13]
[14 15 16]]

Explanation:
NumPy expands the scalar x to match the shape of array a.
The operation a + x adds 10 to each element of a.

Working of Broadcasting in NumPy


Broadcasting applies specific rules to find whether two arrays can be aligned for operations or not
that are:

1. Check Dimensions: Ensure the arrays have the same number of dimensions or expandable
dimensions.
2. Dimension Padding: If arrays have different numbers of dimensions the smaller array is left-
padded with ones.
3. Shape Compatibility: Two dimensions are compatible if they are equal or one of them is 1.

If these conditions aren’t met NumPy will raise a ValueError. Lets see various examples for
broadcasting below:

Example 1: Broadcasting a Scalar to a 1D Array

It creates a NumPy array arr with values [1, 2, 3] and adds a scalar value 1 to each element of the
array using broadcasting.
import numpy as np
arr = [Link]([1, 2, 3])
res = arr + 1
print(res)
Loading Playground...

Output

[2 3 4]

Example 2: Broadcasting a 1D Array to a 2D Array

This example shows how a 1D array a1 is added to a 2D array a2. NumPy automatically expands the
1D array along the rows of the 2D array to perform element-wise addition.

import numpy as np

a = [Link]([2, 4, 6])
b = [Link]([[1, 3, 5], [7, 9, 11]])
res = a + b
print(res) Loading Playground...

Output

[[ 3 7 11]
[ 9 13 17]]

Explanation:
a1 has shape (3,) and a2 has shape (2, 3).
NumPy automatically repeats a1 across both rows of a2 so their shapes match.
Then it adds elements position-wise: [1, 3, 5] + [2, 4, 6] = [3, 7, 11] and [7, 9, 11] + [2, 4, 6] = [9,
13, 17]

Example 3: Broadcasting in Conditional Operations

This example checks each age in the array and assigns "Adult" or "Minor" using [Link]().

import numpy as np

a = [Link]([12, 24, 35, 45, 60, 72])


b = [Link](["Adult", "Minor"])
res = [Link](a > 18, b[0], b[1])
print(res) Loading Playground...

Output
['Minor' 'Adult' 'Adult' 'Adult' 'Adult' 'Adult']

Explanation:
ages > 18 creates a Boolean array by checking every value at once (broadcasting).
[Link]() picks "Adult" for True and "Minor" for False without any loop.
The result is an array labeling each age correctly.

Example 4: Using Broadcasting for Matrix Multiplication

In this example, each element of a 2D matrix is multiplied by the corresponding element in a


broadcasted vector.

import numpy as np
m = [Link]([[1, 2], [3, 4]])
v = [Link]([10, 20])
res = m * v
print(res)
Loading Playground...

Output

[[10 40]
[30 80]]

Explanation:
The vector v is broadcast across each row of m.
Multiplication happens element-wise without loops.
Result is a scaled version of the matrix.

Example 5: Scaling Data with Broadcasting

Consider a real-world scenario where we need to calculate the total calories in foods based on the
amount of fats, proteins and carbohydrates. Each nutrient has a specific caloric value per gram.

Fats: 9 calories per gram (CPG)


Proteins: 4 CPG
Carbohydrates: 4 CPG
Scaling Data with Broadcasting

Left table shows the original data with food items and their respective grams of fats, proteins and
carbs. The array [9, 4, 4] represents the caloric values per gram for fats, proteins and carbs
respectively. This array is being broadcast to match the dimensions of the original data and arrow
indicates the broadcasting operation.

Broadcasting array is multiplied element-wise with each row of the original data.
As a result right table shows the result of the multiplication where each cell represents the caloric
contribution of that specific nutrient in the food item.

import numpy as np

fd = [Link]([ [0.8, 2.9, 3.9],


[52.4, 23.6, 36.5],
[55.2, 31.7, 23.9],
[14.4, 11.0, 4.9] ])

cpg = [Link]([9, 4, 4]) Loading Playground...


res = fd * cpg
print(res)

Output

[[ 7.2 11.6 15.6]


[471.6 94.4 146. ]
[496.8 126.8 95.6]
[129.6 44. 19.6]]

Explanation:
cpg (9, 4, 4) broadcasts across each row of fd.
Each nutrient gram is multiplied by its calorie value.
Result is a matrix showing calorie contribution from fats, proteins and carbs for each food item.
Example 6: Adjusting Temperature Data Across Multiple Locations

Suppose you have a 2D array representing daily temperature readings across multiple cities and you
want to apply a correction factor to each city’s temperature data.

import numpy as np

temp = [Link]([ [30, 32, 34, 33, 31],


[25, 27, 29, 28, 26],
[20, 22, 24, 23, 21] ])

corr = [Link]([1.5, -0.5, 2.0]) Loading Playground...


res = temp + corr[:, None]
print(res)

Output

[[31.5 33.5 35.5 34.5 32.5]


[24.5 26.5 28.5 27.5 25.5]
[22. 24. 26. 25. 23. ]]

Explanation:
corr[:, None] turns the 1D array into a column vector.
NumPy broadcasts this vector down each row of temp.
Each city’s temperatures get adjusted using its corresponding correction factor.

Example 7: Normalizing Image Data

Normalization is important in many real-world scenarios like image processing and machine learning
because it:

1. Centers data by subtracting the mean by ensuring features have zero mean.
2. Scales data by dividing by the standard deviation by ensuring features have unit variance.
3. Improves numerical stability and performance of algorithms like gradient descent.

Let's see how broadcasting simplifies normalization:

import numpy as np

img = [Link]([ [100, 120, 130],


[90, 110, 140],
[80, 100, 120] ])

m = [Link](axis=0)
s = [Link](axis=0) Loading Playground...
res = (img - m) / s
print(res)
Output

[[ 1.22474487 1.22474487 0. ]
[ 0. 0. 1.22474487]
[-1.22474487 -1.22474487 -1.22474487]]

Explanation:
m and s are 1D arrays (mean and std for each column).
NumPy broadcasts them across all rows of img.
(img - m) centers the data.
Dividing by s scales it, giving the normalized values.

Example 8: Centering Data in Machine Learning

Centering data is an important step in many machine learning workflows. Broadcasting helps center
the data efficiently by subtracting the mean from each feature. This example centers each feature by
subtracting its mean using NumPy broadcasting.

import numpy as np

data = [Link]([ [10, 20],


[15, 25],
[20, 30] ])

m = [Link](axis=0) Loading Playground...


res = data - m
print(res)

Output

[[-5. -5.]
[ 0. 0.]
[ 5. 5.]]

Explanation:
m is a 1D array containing the mean of each column.
NumPy broadcasts m across all rows.
Subtracting it centers every feature around zero.

Suggested Quiz 3 Questions

What is broadcasting in NumPy?

A Creating videos from arrays

B Printing large arrays


C Stretching arrays with smaller shapes to perform operations

D Sorting arrays 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
View Explanation
Pradesh (201305) Careers 1Blogs
/3 Technology Web < Previous
Hyderabad Next >
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 APradesh, 201305 Follow
Comment ankurt… Training Subjects DevOps & 13
Program GATE Cloud
School GATE
Article Tags: Numpy Python-numpy Python numpy-arrayManipulation 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 Create a Sparse Matrix with SciPy


Last Updated : 10 Dec, 2025

A sparse matrix is a matrix in which most elements are zeros. Sparse matrices are widely used in
machine learning, natural language processing (NLP), and large-scale data processing, where storing
all zero values is inefficient.
Example of a sparse matrix:

00304
00570
00000
02600

Storing such a matrix as a normal 2D array wastes memory, as most elements are zeros. Instead, we
store only non-zero elements along with their row and column indices (triplets format).
Benefits of using sparse matrices:
Reduced Memory Usage: Only non-zero elements are stored, saving memory.
Faster Computations: Operations can be performed only on non-zero elements, improving speed.

Sparse Matrix Formats in SciPy

The [Link] module provides several formats for storing sparse matrices, each optimized for
different operations:

Format Best For Description

csr_matrix Fast row slicing, math Compressed Sparse Row good for arithmetic and row
operations access.

csc_matrix Compressed Sparse Column efficient for column-based


Fast column slicing
ops.

coo_matrix Easy matrix building Coordinate format using (row, col, value) triples.

lil_matrix Incremental row-wise


List of Lists, modify rows easily before converting.
construction

dia_matrix Diagonal-dominant matrices Stores only diagonals, saves space.


Format Best For Description

dok_matrix Fast item assignment Dictionary-like, ideal for random updates.

Example 1: csr_matrix (Compressed Sparse Row)

CSR format stores non-zero values row-wise, enabling fast row slicing and efficient matrix
operations.

import numpy as np
from [Link] import csr_matrix

d = [Link]([3, 4, 5, 7, 2, 6]) # data


r = [Link]([0, 0, 1, 1, 3, 3]) # rows
c = [Link]([2, 4, 2, 3, 1, 2]) # cols
Loading Playground...
csr = csr_matrix((d, (r, c)), shape=(4, 5))
print([Link]())

Output

[[0 0 3 0 4]
[0 0 5 7 0]
[0 0 0 0 0]
[0 2 6 0 0]]

Explanation: csr_matrix stores only non-zero values with their coordinates and reconstructs full
matrix using toarray().

Example 2: csc_matrix (Compressed Sparse Column)

CSC format stores data column-wise, making column-based operations faster.

import numpy as np
from [Link] import csc_matrix

d = [Link]([3, 4, 5, 7, 2, 6])
r = [Link]([0, 0, 1, 1, 3, 3])
c = [Link]([2, 4, 2, 3, 1, 2])
Loading Playground...
csc = csc_matrix((d, (r, c)), shape=(4, 5))
print([Link]())

Output

[[0 0 3 0 4]
[0 0 5 7 0]
[0 0 0 0 0]
[0 2 6 0 0]]
Explanation: Stores non-zero values in column-compressed format, efficient for column operations.

Example 3: coo_matrix (Coordinate Format)

COO format represents the matrix using (row, col, value) triplets. Useful when constructing matrices
dynamically before converting to CSR/CSC.

import numpy as np
from [Link] import coo_matrix

d = [Link]([3, 4, 5, 7, 2, 6])
r = [Link]([0, 0, 1, 1, 3, 3])
c = [Link]([2, 4, 2, 3, 1, 2])
Loading Playground...
coo = coo_matrix((d, (r, c)), shape=(4, 5))
print([Link]())

Output

[[0 0 3 0 4]
[0 0 5 7 0]
[0 0 0 0 0]
[0 2 6 0 0]]

Explanation: Stores elements as (row, col, value) tuples.

Example 4: lil_matrix (List of Lists)

LIL (List of Lists) format allows efficient row-wise construction. You can easily insert or modify values
before converting the matrix to CSR or CSC for faster computation.

import numpy as np
from [Link] import lil_matrix

lil = lil_matrix((4, 5))


lil[0, 2] = 3
lil[0, 4] = 4
lil[1, 2] = 5
lil[1, 3] = 7 Loading Playground...
lil[3, 1] = 2
lil[3, 2] = 6

print([Link]())

Output

[[0. 0. 3. 0. 4.]
[0. 0. 5. 7. 0.]
[0. 0. 0. 0. 0.]
[0. 2. 6. 0. 0.]]

Explanation: Creates a List of Lists (LIL) matrix and assigns values directly by row and column.
Example 5: dok_matrix (Dictionary of Keys)

DOK (Dictionary of Keys) format is ideal for random assignments. You can assign elements at any
position efficiently, making it perfect for incremental matrix construction.

import numpy as np
from [Link] import dok_matrix

dok = dok_matrix((4, 5))


dok[0, 2] = 3
dok[0, 4] = 4
dok[1, 2] = 5
dok[1, 3] = 7
Loading Playground...
dok[3, 1] = 2
dok[3, 2] = 6

print([Link]())

Output

[[0. 0. 3. 0. 4.]
[0. 0. 5. 7. 0.]
[0. 0. 0. 0. 0.]
[0. 2. 6. 0. 0.]]

Explanation: Internally stored as dictionary {(row, col): value}.

Example 6: dia_matrix (Diagonal Matrix)

DIA (Diagonal) format stores only the diagonals of the matrix. It is very memory-efficient for
diagonal-dominant matrices, where most non-zero elements lie along certain diagonals.

import numpy as np
from [Link] import dia_matrix

data = [Link]([[3, 5, 6, 7]])


offsets = [Link]([0])

dia = dia_matrix((data, offsets), shape=(4, 5)) Loading Playground...


print([Link]())

Output

[[3 0 0 0 0]
[0 5 0 0 0]
[0 0 6 0 0]
[0 0 0 7 0]]

Explanation: Creates a Diagonal (DIA) matrix storing only specified diagonals.

Related Articles:
Compressed Sparse formats CSR and CSC in Python
Python program to Convert a Matrix to Sparse Matrix

Comment A Amiya… Follow 3

Article Tags: Python Python Programs Python-scipy

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

Image Processing with SciPy and NumPy in Python


Last Updated : 15 Jan, 2026

Image processing is used in areas like computer vision and medical imaging, focusing on enhancing
and analyzing digital images. In Python, NumPy treats images as arrays for efficient pixel-level
operations, while SciPy’s ndimage module provides tools for filtering and transformations, enabling
fast and lightweight processing.

Installation
Ensure you have the required libraries installed:

pip install numpy scipy matplotlib imageio scikit-image

NumPy: Handles arrays and numerical computations.


SciPy: Adds advanced scientific and mathematical functions.
Matplotlib: Creates plots and visualizations.
ImageIO: Reads and writes image files.
scikit-image: Provides tools for image processing and analysis.

To download the image used in this article, click here

Opening and Displaying Image


To begin any image processing task, the first step is to load and visualize the image. We'll use
imageio.v3 to read an image and matplotlib to display it.

import imageio.v3 as iio


import [Link] as plt

img = [Link]("[Link]")
[Link](img)
[Link]('off')
Loading Playground...
[Link]()

Output
loaded image

Note: The image must be in the same folder as the Python script otherwise, provide a relative
or full path.

Explanation:
[Link](): loads the image into a NumPy array.
[Link](): visualizes it.
[Link]('off'): hides axes for a cleaner look.

Creating NumPy array from Image


An image is essentially a multi-dimensional NumPy array. Knowing its shape and data type is
important for applying filters and transformations.

import imageio.v3 as iio


import numpy as np

img = [Link]("[Link]")
print("Shape:", [Link])
print("Data type:", [Link]) Loading Playground...

Output

Pixel data type

Explanation: Shape helps understand the image layout (e.g., 266x341x3 for RGB). Data type
(usually uint8) shows pixel value range (0-255).

Creating RAW file


A .raw file stores raw binary data from an image sensor or matrix. It's useful when dealing with
uncompressed data in image pipelines.

import imageio.v3 as iio


import numpy as np
img = [Link]("[Link]")
[Link]("[Link]")
Loading Playground...
Output

RAW saved

Explanation: tofile() saves the image pixel data as a binary file, useful for low-level image
processing.

Opening RAW File


To work with .raw files, we use [Link]() to reconstruct the image data into a usable NumPy
array.

import imageio.v3 as iio


import numpy as np

orig = [Link]("[Link]")
h, w, c = [Link]

flat = [Link]('[Link]', dtype=np.uint8)


Loading Playground...
img=[Link]((h,w,c))
print([Link])

Output

Binary loaded

Explanation: fromfile() reads binary data and the array must be reshaped manually if you want to
visualize it (e.g., reshape to original height × width × channels).

Getting Statistical Information


Understanding the min, max and average pixel intensity gives insight into brightness, contrast and
histogram distribution of the image.

import imageio.v3 as iio


import numpy as np
img = [Link]("[Link]")

print("Max:", [Link]())
print("Min:", [Link]())
Loading Playground...
print("Mean:", [Link]())

Output
Pixel stats

Explanation: Max and min values indicate contrast and Mean gives an overall idea of brightness.

Cropping the Image


Cropping helps focus on a particular region of interest (ROI) in an image by slicing the NumPy array.

import imageio.v3 as iio


import [Link] as plt

img = [Link]("[Link]")
x, y, _ = [Link]

# Crop center region


crop = img[h//4 : 3*h//4, w//4 : 3*w//4]
Loading Playground...
[Link](crop)
[Link]('off')
[Link]("Cropped Raccoon")
[Link]()

Output

Explanation:
[Link]: gives image dimensions (height x, width y, channels _).
img[h//4 : 3*h//4, w//4 : 3*w//4]: selects a central region using slicing.
[Link](): visualizes the cropped section.

Flipping Image (Vertical)


Flipping an image (up-down or left-right) is a common data augmentation technique in image
preprocessing.

import imageio.v3 as iio


import [Link] as plt
import numpy as np

img = [Link]("[Link]")
flipped = [Link](img)
[Link](flipped)
[Link]('off') Loading Playground...
[Link]("Flipped Image (Up-Down)")
[Link]()

Output

Explanation: [Link]() flips the image along the vertical axis.

Filtering images
Filtering is a fundamental technique in image processing used to enhance or suppress certain
features. It helps in tasks like smoothing, sharpening and edge detection.

1. Gaussian Blur

Blurring helps reduce image noise and details using a Gaussian kernel. It’s useful in preprocessing
steps like edge detection or thresholding.

from [Link] import gaussian_filter


import imageio.v3 as iio
import [Link] as plt
import numpy as np

img = [Link]("[Link]")
blurred = gaussian_filter(img, sigma=5)
Loading Playground...
[Link]([Link](np.uint8))
[Link]('off')
[Link]("Gaussian Blurred")
[Link]()

Output
Explanation: gaussian_filter(img, sigma=5) smooths the image using a Gaussian kernel. sigma
controls the intensity of blur and converts to uint8 before display to ensure proper color rendering.

2. Sharpening Image (Unsharp Masking)

Sharpening increases contrast between edges to enhance details and clarity. Unsharp masking
subtracts a blurred version from the original.

from [Link] import rgb2gray, rgba2rgb


from [Link] import gaussian_filter
import imageio.v3 as iio
import [Link] as plt
import numpy as np

img = [Link]("[Link]")
if [Link][-1] == 4:
img = rgba2rgb(img)

gray = rgb2gray(img).astype(float) Loading Playground...


blur = gaussian_filter(gray, 5)
alpha = 30
sharp = gray + alpha * (gray - gaussian_filter(blur, 1))

[Link](sharp, cmap='gray')
[Link]('off')
[Link]("Sharpened Image")
[Link]()

Output

Explanation:
Converts image to grayscale using rgb2gray.
gray - gaussian_filter(blur, 1) extracts edge details and adds edge details back using alpha
scaling Unsharp Masking.

Denoising Images
Image denoising removes random noise to enhance image quality, particularly useful in low-light
photography or scanned documents.

1. Add noise

Artificial noise is added to simulate a noisy environment, commonly seen in real-world low-light or
sensor-imperfect images.

import numpy as np
import imageio.v3 as iio
import [Link] as plt
from [Link] import rgb2gray, rgba2rgb

img = [Link]("[Link]")
if [Link][-1] == 4:
img = rgba2rgb(img)

gray = rgb2gray(img).astype(float) Loading Playground...


noise_img = gray + 0.9 * [Link]() * [Link]([Link])

[Link](noise_img, cmap='gray')
[Link]('off')
[Link]("Noisy Image")
[Link]()

Output

Explanation: Adds random values scaled by image standard deviation to simulate real-world noise
(e.g., from low-light sensors).

2. Gaussian Denoising

Gaussian filtering smooths the image by averaging pixel values with its neighbors using a Gaussian
kernel, effectively reducing high-frequency noise.

from scipy ndimage import gaussian filter


from [Link] import gaussian_filter
import [Link] as plt

denoised = gaussian_filter(noise_img, sigma=2.2)


[Link](denoised, cmap='gray')
[Link]('off')
[Link]("Denoised (Gaussian)") Loading Playground...
[Link]()

Explanation: Smooths the image using a Gaussian kernel to reduce high-frequency noise while
preserving structure.

Edge Detection using Sobel Filter


Sobel edge detection identifies image edges by computing intensity gradients using 3×3 kernels. It
highlights boundaries by combining horizontal and vertical changes, aiding in tasks like
segmentation and object detection.

import numpy as np
import [Link] as plt
from [Link] import rotate, gaussian_filter, sobel

im = [Link]((300, 300))
im[64:-64, 64:-64] = 1

im = rotate(im, 30, mode='constant')


im = gaussian_filter(im, sigma=7)

[Link](im, cmap='gray')
[Link]('off')
Loading Playground...
[Link]("Original Synthetic Image")
[Link]()

dx = sobel(im, axis=0, mode='constant')


dy = sobel(im, axis=1, mode='constant')
sobel_edges = [Link](dx, dy)

[Link](sobel_edges, cmap='gray')
[Link]('off')
[Link]("Sobel Edge Detection")
[Link]()

Output
Original Synthetic Image

Sober Edge Detection

Explanation: Creates a synthetic image, applies Gaussian blur, then detects edges using Sobel filters
by computing horizontal and vertical gradients and combining them to highlight edge intensity.

Related Articles:

Multidimensional image processing using Scipy in Python


Image processing with Scikit-image in Python

Comment A abhish… Follow

Article Tags: Python Image-Processing

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

Introduction to Seaborn - Python


Last Updated : 30 Oct, 2025

Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides
beautiful default styles and color palettes to make statistical plots more attractive. It is built on top
matplotlib library and is also closely integrated with the data structures from pandas.

Seaborn aims to make visualization the central part of exploring and understanding data. It provides
dataset-oriented APIs so that we can switch between different visual representations for the same
variables for a better understanding of the dataset.

Different categories of plot in Seaborn


Plots are basically used for visualizing the relationship between variables. Those variables can be
either completely numerical or a category like a group, class, or division. Seaborn divides the plot
into the below categories -

Relational plots: This plot is used to understand the relation between two variables.
Categorical plots: This plot deals with categorical variables and how they can be visualized.
Distribution plots: This plot is used for examining univariate and bivariate distributions
Regression plots: The regression plots in Seaborn are primarily intended to add a visual guide
that helps to emphasize patterns in a dataset during exploratory data analyses.
Matrix plots: A matrix plot is an array of scatterplots.
Multi-plot grids: It is a useful approach to draw multiple instances of the same plot on different
subsets of the dataset.

Installation of Seaborn Library


For Python environment :

pip install seaborn

For conda environment :

conda install seaborn

Dependencies for Seaborn Library

There are some libraries that must be installed before using Seaborn. Here we will list out some
basics that are a must for using Seaborn.

Python 3.6 or higher


numpy (>= 1.13.3)
scipy (>= 1.0.1)
pandas (>= 0.22.0)
matplotlib (>= 2.1.2)

However, we must note that if try to use Seaborn

Some basic plots using seaborn


Histplot: Seaborn Histplot is used to visualize the univariate set of distributions(single variable). It
plots a histogram, with some other variations like kdeplot and rugplot. The Histplot function takes
several arguments but the important ones are

data: This is the array, series, or dataframe that you want to visualize. It is a required
parameter.
x: This specifies the column in the data to use for the histogram. If your data is a dataframe,
you can specify the column by name.
y: This specifies the column in the data to use for the histogram when you want to create a
bivariate histogram. By default, it is set to None, meaning that a univariate histogram will be
plotted.
bins: This specifies the number of bins to use when dividing the data into intervals for
plotting. By default, it is set to "auto", which uses an algorithm to determine the optimal
number of bins.
kde: This parameter controls whether to display a kernel density estimate (KDE) of the data
in addition to the histogram. By default, it is set to False, meaning that a KDE will not be
plotted.

import numpy as np
import seaborn as sns

[Link](style="white")

# Generate a random univariate dataset


rs = [Link](10)
d = [Link](size=100)

# Plot a simple histogram and kde


[Link](d, kde=True, color="m")

Output
Histogram with seaborn

Distplot: Seaborn distplot is used to visualize the univariate set of distributions(Single features) and
plot the histogram with some other variations like kdeplot and rugplot.

The function takes several parameters, but the most important ones are:

a: This is the array, series, or list of data that you want to visualize. It is a required parameter.
bins: This specifies the number of bins to use when dividing the data into intervals for
plotting. By default, it is set to "auto", which uses an algorithm to determine the optimal
number of bins.
kde: This parameter controls whether to display a kernel density estimate (KDE) of the data
in addition to the histogram. By default, it is set to True, meaning that a KDE will be plotted.
hist: This parameter controls whether to display the histogram of the data. By default, it is
set to True, meaning that a histogram will be plotted.

import numpy as np
import seaborn as sns

[Link](style="white")

# Generate a random univariate dataset


rs = [Link](10)
d = [Link](size=100)

# Define the colors to use


colors = ["r", "g", "b"]

# Plot a histogram with multiple colors


[Link](d, kde=True, hist=True, bins=10,
rug=True,hist_kws={"alpha": 0.3,
"color": colors[0]},
kde_kws={"color": colors[1], "lw": 2},
rug_kws={"color": colors[2]})

Output
Distplot using seaborn

Note: The distplot function has been deprecated in the newer version of the Seaborn Library

Lineplot: The line plot is one of the most basic plots in the seaborn library. This plot is mainly used
to visualize the data in the form of some time series, i.e. in a continuous manner.

import seaborn as sns


import [Link] as plt

[Link](style="dark")
fmri = sns.load_dataset("fmri")

# Plot the responses for different\


# events and regions
[Link](x="timepoint",
y="signal",
hue="region",
style="event",
data=fmri)
[Link]()

Output
Lineplot using seaborn

Lmplot: The lmplot is another most basic plot. It shows a line representing a linear regression
model along with data points on the 2D space and x and y can be set as the horizontal and vertical
labels respectively.

import seaborn as sns

[Link](style="ticks")

# Loading the dataset


df = sns.load_dataset("anscombe")

# Show the results of a linear regression


[Link](x="x", y="y", data=df)

Output

Lmplot using seaborn

Related Articles:

Maplotlib Library
Pandas
Comment 09amit Follow 17

Article Tags: Python Computer Subject AI-ML-DS python-modules

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

Plotting graph using Seaborn | Python


Last Updated : 30 Sep, 2025

Seaborn is a Python data visualization library built on top of Matplotlib. It provides a high-level
interface for drawing attractive, informative statistical graphics. Unlike Matplotlib, Seaborn works
seamlessly with Pandas DataFrames, making it a preferred tool for quick exploratory data analysis
and advanced statistical plotting.

Key Features

Comes with built-in datasets like iris, tips, etc.


Provides statistical plots such as boxplots, violin plots, swarm plots, etc.
Handles categorical data visualization better than Matplotlib.
Supports aesthetic customization (themes, color palettes, styles).
Simplifies working with DataFrames by auto-labeling axes.

Different Plots in Seaborn


Let's see the various types of plots in seaborn,

1. Strip Plot

A strip plot is a categorical scatter plot where data points are plotted along one categorical axis. It is
useful for visualizing the distribution of values but may suffer from overlapping points.
Applications
Used when we want to visualize raw distribution of numerical data across categories.
Helpful for detecting clusters or general spread of values.

Advantages
Simple and easy to interpret.
Shows individual data points clearly.

Limitations
Overlapping points may cause loss of clarity in dense datasets.

import [Link] as plt


import seaborn as sns

x = ['sun', 'mon', 'fri', 'sat', 'tue', 'wed', 'thu']


y = [5, 6.7, 4, 6, 2, 4.9, 1.8]

ax = [Link](x=x, y=y)
[Link](xlabel='Days', ylabel='Amount Spent')
[Link]('Daily Spending (Custom Data)')
[Link]()

Output:

Simple Plot

2. Swarm Plot

A swarm plot is similar to a strip plot, but points are arranged to avoid overlap. This ensures all data
points are visible, making it more informative.
Applications
Useful when dataset is small/medium and we want to show all observations.
Comparing sub-groups clearly without stacking.

Advantages
Prevents overlap of data points.
Provides clearer visual insight than strip plot.

Limitations
Can be slow for large datasets.
May look cluttered when categories have thousands of points.

[Link](style="whitegrid")
iris = sns.load_dataset("iris")
[Link](x="species", y="sepal_length", data=iris)
[Link]("Swarm Plot of Sepal Length by Species")
[Link]()

Output:
Swarm Plot

3. Bar Plot

A bar plot shows the average (by default mean) of a numerical variable across categories. It can use
different estimators (mean, median, std, etc.) for aggregation.
Applications
Comparing average values across categories.
Displaying results of group-by operations visually.

Advantages
Easy to interpret and widely used.
Flexible can use different statistical functions.

Limitations
Does not show individual data distribution.
Can hide variability when using only mean.

tips = sns.load_dataset("tips")
[Link](x="sex", y="total_bill", data=tips, palette="plasma")
[Link]("Average Total Bill by Gender")
[Link]()

Output:
Bar Plot

4. Count Plot

A count plot simply counts the occurrences of each category. It is like a histogram for categorical
variables.
Applications
Checking frequency distribution of categorical values.
Understanding class imbalance in data.

Advantages
Very simple and quick to interpret.
No need for numerical data, only categorical required.

Limitations
Cannot display numerical spread inside categories.

tips = sns.load_dataset("tips")
[Link](x="sex", data=tips)
[Link]("Count of Gender in Dataset")
[Link]()

Output:
Count Plot

5. Box Plot

A box plot (or whisker plot) summarizes numerical data using quartiles, median and outliers. It helps
in detecting variability and spread.
Applications
Detecting outliers.
Comparing spread of distributions across categories.

Advantages
Highlights summary statistics effectively.
Useful for large datasets.

Limitations
Does not show exact data distribution shape.

tips = sns.load_dataset("tips")
[Link](x="day", y="total_bill", data=tips, hue="smoker")
[Link]("Total Bill Distribution by Day & Smoking Status")
[Link]()

Output:
Box Plot

6. Violin Plot

A violin plot combines a box plot with a density plot, showing both summary stats and distribution
shape.
Applications
Comparing distributions more deeply than boxplot.
Helpful for detecting multimodal distributions.

Advantages
Shows both summary statistics and data distribution.
Easier to see differences in distribution shapes.

Limitations
Can be harder to interpret for beginners.
May be misleading if sample size is small.

tips = sns.load_dataset("tips")
[Link](x="day", y="total_bill", data=tips, hue="sex", split=True)
[Link]("Violin Plot of Total Bill by Day and Gender")
[Link]()

Output:
Violin Plot

7. Strip Plot with Hue

This is an enhanced strip plot where categories are further divided using hue. It allows comparing
multiple sub-groups within a category.
Applications
Comparing subgroups inside categories.
Visualizing interaction between two categorical variables.

Advantages
Adds extra dimension to strip plot.
Useful for multivariate visualization.

Limitations
Overlap issue exists.

tips = sns.load_dataset("tips")
[Link](x="day", y="total_bill", data=tips,
jitter=True, hue="smoker", dodge=True)
[Link]("Total Bill Distribution with Smoking Status")
[Link]()

Output:
Strip Plot with Hue

Applications
Exploratory Data Analysis (EDA): Identifying trends, outliers and patterns.
Feature Analysis: Comparing numerical features across categories.
Data Presentation: Creating professional, publication-ready plots.
Model Preparation: Checking class imbalance or spread before training models.

Comment S saloni… Follow 18

Article Tags: Machine Learning 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
a Visualization Tutorial With Python Types Matplotlib Altair Plotly Computer Vision OpenCV Computer Graphics Tutorial Deep Learn

Plotting with Seaborn and Matplotlib


Last Updated : 23 Jul, 2025

Matplotlib and Seaborn are two of the most powerful Python libraries for data visualization. While
Matplotlib provides a low-level, flexible approach to plotting, Seaborn simplifies the process by
offering built-in themes and functions for common plots.

Before diving into plotting, ensure you have both libraries installed:

pip install matplotlib seaborn

After installation, Import them in your script:

import [Link] as plt


import seaborn as sns

Basic plotting with matplotlib


Matplotlib allows you to create simple plots using [Link](). Here’s an example of plotting lines and
dots:

import [Link] as plt

[Link]([0, 1], [10, 11], label='Line 1')


[Link]([0, 1], [11, 10], label='Line 2')
[Link]([0, 1], [10.5, 10.5], color='blue', marker='o', label='Dots')
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Simple Line and Dot Plot')
[Link]()
[Link]()
Explanation:
[Link]([0, 1], [10, 11], label='Line 1') plots a line moving upward from (0,10) to (1,11).
[Link]([0, 1], [11, 10], label='Line 2') plots a line moving downward from (0,11) to (1,10).
label='Line 1' / 'Line 2' assigns names for the legend.

Why Combine matplotlib and seaborn?


Seaborn makes plotting easier, but it is built on top of Matplotlib, so we can use both together for
better results:

Customization: Matplotlib lets us fully control the plot (axes, labels, grid, colors, etc.).
Better Looks: Seaborn has built-in themes and styles that make plots look nicer.
Statistical Plots: Seaborn includes special plots like violin plots and KDE plots.
More Flexibility: Matplotlib allows extra customization and combining multiple plots.

Enhancing matplotlib with seaborn styles


Seaborn simplifies data visualization with built-in themes and high-level functions.

Example 1. Applying seaborn style to matplotlib plots

import [Link] as plt


import seaborn as sns

# Apply Seaborn theme


sns.set_theme(style="darkgrid")

# Creating a simple Matplotlib plot


x = [1, 2, 3, 4, 5]
y = [10, 12, 15, 18, 22]
Loading Playground...
[Link](x, y, marker='o', linestyle='-', color='blue', label="Trend")
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Matplotlib Plot with Seaborn Theme")
[Link]()
[Link]()
Output:

Explanation:
sns.set_theme(style="darkgrid") applies a Seaborn theme for a cleaner look.
The plot consists of a simple line with markers, enhanced with labels and a legend.

Example 2. Customizing a seaborn plot with matplotlib

import [Link] as plt


import seaborn as sns
import panda as pd

data = [Link]({
'Year': [2018, 2019, 2020, 2021, 2022],
'Sales': [100, 150, 200, 250, 300]
})

[Link](figsize=(8, 5))
[Link](x='Year', y='Sales', data=data, marker='o')
Loading Playground...

# Customizing using Matplotlib


[Link]("Yearly Sales Growth", fontsize=14, fontweight='bold')
[Link]("Year", fontsize=12)
[Link]("Total Sales", fontsize=12)
[Link](rotation=45)
[Link](True, linestyle='--')

[Link]()

Output:
Explanation:
Seaborn’s [Link]() creates a line plot from a DataFrame.
Matplotlib functions customize the title, axis labels and grid styling.

Example 3. Overlaying seaborn and matplotlib plots

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

x = [Link](0, 10, 20)


y = [Link](x)

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

# Seaborn Line Plot


[Link](x=x, y=y, color='blue', label='SineLoading
Wave')Playground...

# Matplotlib Scatter Plot


[Link](x, y, color='red', marker='o', label="Data Points")

[Link]("Seaborn Line Plot with Matplotlib Scatter Overlay")


[Link]("X-axis")
[Link]("Y-axis")
[Link]()
[Link]()

Output:
Explanation:
[Link]() creates a smooth sine wave.
[Link]() overlays red data points for better visualization.

Example 4. Enhancing Seaborn Histogram with Matplotlib Annotations

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

data = [Link](1000)

[Link](figsize=(8, 5))
[Link](data, kde=True, bins=30, color='purple')

# Adding Mean Line using Matplotlib


mean_value = [Link](data) Loading Playground...
[Link](mean_value, color='red', linestyle='dashed', linewidth=2)
[Link](mean_value + 0.1, 50, f'Mean: {mean_value:.2f}', color='red')

[Link]("Distribution with Seaborn and Matplotlib Customization")


[Link]("Value")
[Link]("Frequency")
[Link]()

Output:
Explanation:
[Link]() creates a histogram with a KDE curve.
[Link]() draws a dashed red line at the mean value.
[Link]() annotates the mean value on the plot.

Comment V vishak… Follow 1

Article Tags: Data Visualization

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

Seaborn | Style And Color


Last Updated : 29 Jan, 2021

Seaborn is a statistical plotting library in python. It has beautiful default styles. This article deals
with the ways of styling the different kinds of plots in seaborn.

Seaborn Figure Styles


This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic
elements.
The ways of styling themes are as follows:
white
dark
whitegrid
darkgrid
ticks

Set the background to be white:


Given style with the help of countplot and the dataset is present in seaborn by default.
load_dataset() function is used to load the dataset. set_style() function is used for plot styling.

import seaborn as sns


import [Link] as plt

# load the tips dataset present by default in seaborn


tips = sns.load_dataset('tips')
sns.set_style('white')

# make a countplot
[Link](x ='sex', data = tips)

Output:

Set the background to ticks:


Ticks appear on the sides of the plot on setting it as set_style('ticks'). palette attribute is used to set
the color of the bars. It helps to distinguish between chunks of data.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
sns.set_style('ticks')
[Link](x ='sex', data = tips, palette = 'deep')

Output:

Set the background to be darkgrid:


Darkgrid appear on the sides of the plot on setting it as set_style('darkgrid'). palette attribute is used
to set the color of the bars. It helps to distinguish between chunks of data.

import seaborn as sns


import [Link] as plt

# load the tips dataset present by default in seaborn


tips = sns.load_dataset('tips')
sns.set_style('darkgrid')

# make a countplot
[Link](x ='sex', data = tips)

Output:

Set the background to be Whitegrid:


Whitegrid appears on the sides of the plot on setting it as set_style('whitegrid'). palette attribute is
used to set the color of the bars. It helps to distinguish between chunks of data.

import seaborn as sns


import [Link] as plt
# load the tips dataset present by default in seaborn
tips = sns.load_dataset('tips')
sns.set_style('whitegrid')

# make a countplot
[Link](x ='sex', data = tips)

Output:

Removing Axes Spines


The despine() is a function that removes the spines from the right and upper portion of the plot by
default. [Link](left = True) helps remove the spine from the left.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
[Link](x ='sex', data = tips)
[Link]()

Output

Size and aspect


Non grid plot: The figure() is a matplotlib function used to plot the figures. The figsize is used to set
the size of the figure.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
[Link](figsize =(12, 3))
[Link](x ='sex', data = tips) Loading Playground...

Output:

Grid type plot: This example shows a regression plot of tips vs the total_bill from the dataset. lmplot
stands for linear model plot and is used to create a regression plot. x ='total_bill' sets the x axis to
total_bill. y='tip' sets the y axis to tips. size=2 is used to the size(the height)of the plot. aspect is used
to set the width keeping the width constant.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
[Link](x ='total_bill', y ='tip', size = 2, aspect = 4, data = tips)
Loading Playground...

Output:

Scale and Context


The set_context() allows us to override default parameters. This affects things like the size of the
labels, lines, and other elements of the plot, but not the overall style.
The context are:

poster
paper
notebook
talk

Example 1: using poster.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
sns.set_context('poster', font_scale = 2)
[Link](x ='sex', data = tips, palette ='coolwarm')
Loading Playground...
Output:

Example 2: Using paper.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
sns.set_context('paper', font_scale = 2)
[Link](x ='sex', data = tips, palette = 'coolwarm')

Output:

Example 3: Using notebook.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
sns.set_context('notebook', font_scale = 2)
[Link](x ='sex', data = tips, palette ='coolwarm')

Output:
Example 4: Using talk.

import seaborn as sns


import [Link] as plt

tips = sns.load_dataset('tips')
sns.set_context('talk', font_scale = 2)
[Link](x ='sex', data = tips, palette ='coolwarm')

Output:

Comment C Choco… Follow 6

Article Tags: Machine Learning 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
Courses CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Subjects
Campus GATE DevOps &
Training School Cloud
Program Subjects GATE
Software and Trending
Tools Technologies

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Search...
Tutorials
Practice V
Jobs
Data Science Tutotrial Maths Statistics Big Data Machine Learning AI NumPy Pandas Data Analysis Deep Learning

Seaborn - Color Palette


Last Updated : 8 Apr, 2025

In this article, We are going to see seaborn color_palette(), which can be used for coloring the plot.
Using the palette we can generate the point with different colors.
Example:

import seaborn as sns


import [Link] as plt

# Set a Seaborn color palette


sns.set_palette("Set2")

# Create some example data


data = [3, 5, 7, 9, 2, 4, 6, 8]

# Create a simple bar plot using the set color palette


[Link](x=range(len(data)), y=data)

[Link]()

Output:

Color Palette

Explanation:
sns.set_palette("Set2"): This sets the color palette to "Set2", one of Seaborn's predefined color
palettes.
[Link](): This creates a bar plot using the data with the selected color palette.
[Link](): This displays the plot.
Syntax:

seaborn.color_palette( palette=None , n_colors=None , desat=None)

Parameters:
palette: Name of palette or None to return current palette.
n_colors: Number of colors in the palette.
desat: Proportion to desaturate each color.

Returns: list of RGB tuples or [Link]

Seaborn Color Palette Types


Seaborn offers several predefined color palettes that can be broadly classified into different
categories based on their intended use and the types of visualization.

We can classify the different ways for using color_palette() types −

Qualitative
Sequential
Diverging

1. Qualitative

A qualitative palette is used when the variable is categorical in nature, the color assigned to each
group need to be distinct. Each possible value of the variable is assigned one color from a qualitative
palette within a plot as shown in figure.

from matplotlib import pyplot as plt


import seaborn as sns

cp = sns.color_palette()
[Link](cp)
[Link]()
Output:

2. Sequential

In sequential palettes color moved sequentially from a lighter to a darker. When the variable
assigned to be colored is numeric or has inherently ordered values, then it can be depicted with a
sequential palette as shown in figure.

from matplotlib import pyplot as plt


import seaborn as sns

[Link](sns.color_palette("Greys"))
[Link]()

Output:

3. Diverging

When we work on mixed value like +ve and -ve(low and high values) then diverging palette is the
best suit for visualization.

from matplotlib import pyplot as plt


from matplotlib import pyplot as plt
import seaborn as sns

[Link](sns.color_palette("terrain_r", 7))
[Link]()

Output:

Let's understand this with some examples:


In the below example we have used sns.color_palette() to construct a colormap and [Link]() to
display the colors present in the colormap with "deep" attributes.

import pandas as pd
import seaborn as sns

[Link](sns.color_palette("deep", 10))

Output:

Example 2: In this example, we have used sns.color_palette() to construct a colormap and


[Link]() to display the colors present in the colormap with "muted" attributes.

import pandas as pd
import seaborn as sns

[Link](sns.color_palette("muted", 10))

Output:

Example 3: In this example, we have used sns.color_palette() to construct a colormap and


[Link]() to display the colors present in the colormap with "bright" attributes.

import pandas as pd
import seaborn as sns

[Link](sns.color_palette("bright", 10))

Output:

Example 4: In this example, we have used sns.color_palette() to construct a colormap and


[Link]() to display the colors present in the colormap with "dark" attributes.

import pandas as pd
import seaborn as sns

[Link](sns.color_palette("dark", 10))
Output:

In this example, we have used sns.color_palette() to construct a colormap and [Link]() to


display the colors present in the colormap with "BuGn_r" attributes.

import pandas as pd
import seaborn as sns

[Link](sns.color_palette("BuGn_r", 10))

Output:

If we want to create our own color palette and set it as the current color palette , we can do as
following:

import pandas as pd
import seaborn as sns

color = ["green", "White", "Red", "Yellow", "Green", "Grey"]


sns.set_palette(color)
[Link](sns.color_palette())

Output:

Comment K kumar… Follow 4

Article Tags: Data Science 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
a Visualization Tutorial With Python Types Matplotlib Altair Plotly Computer Vision OpenCV Computer Graphics Tutorial Deep Learn

Python - [Link]() method


Last Updated : 15 Jul, 2025

Prerequisite: Seaborn Programming Basics


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.

[Link]() :

FacetGrid class helps in visualizing distribution of one variable as well as the relationship between
multiple variables separately within subsets of your dataset using multiple panels.
A FacetGrid can be drawn with up to three dimensions ? row, col, and hue. The first two have
obvious correspondence with the resulting array of axes; think of the hue variable as a third
dimension along a depth axis, where different levels are plotted with different colors.
FacetGrid object takes a dataframe as input and the names of the variables that will form the row,
column, or hue dimensions of the grid. The variables should be categorical and the data at each
level of the variable will be used for a facet along that axis.

[Link]( data, \*\*kwargs)

[Link] uses many arguments as input, main of which are described below in form of
table:

Value
Argument
Description

Tidy ("long-form") dataframe where each column is a


data DataFrame
variable and each row is an observation.

Variables that define subsets of the data, which will be


row, col, hue drawn on separate facets in the grid. See the ``*_order`` strings
parameters to control the order of levels of this variable.

Colors to use for the different levels of the ``hue`` palette name, list, or dict,
palette
variable. optional
Below is the implementation of above method:
Example 1:
# importing packages
import seaborn
import [Link] as plt

# loading of a dataframe from seaborn


df = seaborn.load_dataset('tips')

############# Main Section #############


# Form a facetgrid using columns with a hue
graph = [Link](df, col ="sex", hue ="day")
Loading Playground...
# map the above form facetgrid with some attributes
[Link]([Link], "total_bill", "tip", edgecolor ="w").add_legend()
# show the object
[Link]()

# This code is contributed by Deepanshu Rustagi.

Output :

Example 2:

# importing packages
import seaborn
import [Link] as plt

# loading of a dataframe from seaborn


df = seaborn.load_dataset('tips')

############# Main Section #############


# Form a facetgrid using columns with a hue
graph = [Link](df, row ='smoker', colLoading
='time')
Playground...
# map the above form facetgrid with some attributes
[Link]([Link], 'total_bill', bins = 15, color ='orange')
# show the object
[Link]()

# This code is contributed by Deepanshu Rustagi.


Output :

Example 3:

# importing packages
import seaborn
import [Link] as plt

# loading of a dataframe from seaborn


df = seaborn.load_dataset('tips')

############# Main Section #############


# Form a facetgrid using columns with a hue
graph = [Link](df, col ='time', hue ='smoker')
Loading Playground...
# map the above form facetgrid with some attributes
[Link]([Link], "total_bill", "tip").add_legend()
# show the object
[Link]()

# This code is contributed by Deepanshu Rustagi.

Output :
Comment D deepa… Follow 14

Article Tags: Data Visualization AI-ML-DS Python-Seaborn AI-ML-DS With 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
a Visualization Tutorial With Python Types Matplotlib Altair Plotly Computer Vision OpenCV Computer Graphics Tutorial Deep Learn

Python - [Link]() method


Last Updated : 15 Jul, 2025

Prerequisite: Seaborn Programming Basics


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.

[Link]() :

Subplot grid for plotting pairwise relationships in a dataset.


This class maps each variable in a dataset onto a column and row in a grid of multiple axes.
Different axes-level plotting functions can be used to draw bivariate plots in the upper and lower
triangles, and the marginal distribution of each variable can be shown on the diagonal.
It can also represent an additional level of conditionalization with the hue parameter, which plots
different subsets of data in different colors. This uses color to resolve elements on a third
dimension, but only draws subsets on top of each other and will not tailor the hue parameter for
the specific visualization the way that axes-level functions that accept hue will.

[Link]( data, \*\*kwargs)

[Link] uses many arguments as input, main of which are described below in form of table:

Arguments Description
Value

Tidy (long-form) dataframe where each column is a variable and


data DataFrame
each row is an observation.

string (variable name),


hue Variable in ``data`` to map plot aspects to different colors.
optional

Set of colors for mapping the ``hue`` variable. If a dict, keys dict or seaborn color
palette
should be values in the ``hue`` variable. palette

Variables within ``data`` to use, otherwise use every column list of variable names,
vars
with a numeric datatype. optional

dropna Drop missing values from the data before plotting. boolean, optional
Below is the implementation of above method:
Example 1:

# importing packages
import seaborn
import [Link] as plt

# loading dataset
df = seaborn.load_dataset('tips')

# PairGrid object with hue


graph = [Link](df, hue ='day')
# type of graph for diagonal
graph = graph.map_diag([Link])
# type of graph for non-diagonal
graph = graph.map_offdiag([Link])
# to add legends
graph = graph.add_legend()
# to show
[Link]()
# This code is contributed by Deepanshu Rusatgi.

Output :

Example 2:
# importing packages
import seaborn
import [Link] as plt

# loading dataset
df = seaborn.load_dataset('tips')

# PairGrid object with hue


graph = [Link](df)
# type of graph for non-diagonal(upper part)
graph = graph.map_upper([Link]) Loading Playground...
# type of graph for non-diagonal(lower part)
graph = graph.map_lower([Link])
# type of graph for diagonal
graph = graph.map_diag([Link], lw = 2)
# to show
[Link]()
# This code is contributed by Deepanshu Rusatgi.

Output:
Comment D deepa… Follow 7

Article Tags: Data Visualization AI-ML-DS Python-Seaborn AI-ML-DS With 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 for Machine Learning Machine Learning with R Machine Learning Algorithms EDA Math for Machine Learning Machine Learning Inte

Relational plots in Seaborn - Part I


Last Updated : 21 Jul, 2021

Relational plots are used for visualizing the statistical relationship between the data points.
Visualization is necessary because it allows the human to see trends and patterns in the data. The
process of understanding how the variables in the dataset relate each other and their relationships
are termed as Statistical analysis.
Seaborn, unlike to matplotlib, also provides some default datasets. In this article, we will be using a
default dataset named 'tips'. This dataset gives information about people who had food at some
restaurant and whether they left tip for waiters or not, their gender and whether they do smoke or
not, and more.
Let us have a look to the dataset.

# importing the library


import seaborn as sns

# reading the dataset


data = sns.load_dataset('tips')

# printing first five entries


print([Link]())

Output :

total_bill tip sex smoker day time size


0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

To draw the relational plots seaborn provides three functions. These are:
relplot()
scatterplot()
lineplot()

[Link]()
This function provides us the access to some other different axes-level functions which shows the
relationships between two variables with semantic mappings of subsets.
Syntax :

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

Parameters :
Parameter Value Use

x, y numeric Input data variables

Data Dataframe Dataset that is being used.

hue, size, name in data;


Grouping variable that will produce elements with different colors.
style optional

scatter or line;
kind defines the type of plot, either scatterplot() or lineplot()
default : scatter

names of
row, col variables in data; Categorical variables that will determine the faceting of the grid.
optional

“Wrap” the column variable at this width, so that the column facets
col_wrap int; optional
span multiple rows.

row_order, lists of strings;


Order to organize the rows and columns of the grid.
col_order optional

name, list, or dict;


palette Colors to use for the different levels of the hue variable.
optional

hue_order list; optional Specified order for the appearance of the hue variable levels.

tuple or
Normalization in data units for colormap applied to the hue variable
hue_norm Normalize object;
when it is numeric.
optional

list, dict, or tuple;


sizes determines the size of each point in the plot.
optional

size_order list; optional Specified order for appearance of the size variable levels

tuple or
Normalization in data units for scaling plot objects when the size
size_norm Normalize object;
variable is numeric.
optional

If “brief”, numeric hue and size variables will be represented with a


“brief”, “full”, or sample of evenly spaced values. If “full”, every group will get an entry
legend
False; optional in the legend. If False, no legend data is added and no legend is
drawn.

height scalar; optional Height (in inches) of each facet.

Aspect scalar; optional Aspect ratio of each facet, i.e. width/height

facet_kws dict; optional Dictionary of other keyword arguments to pass to FacetGrid.

key, value Other keyword arguments are passed through to the underlying
kwargs
pairings plotting function.
Example 1: Visualizing the most basic plot to show all the data points in tips dataset.

# importing the library


import seaborn as sns

# selecting style
[Link](style ="ticks")

# reading the dataset


tips = sns.load_dataset('tips') Loading Playground...

# plotting a simple visualization of data points


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

Output :

Example 2: Grouping data points on the basis of category, here as time.

# importing the library


import seaborn as sns

# selecting style
[Link](style ="ticks")

# reading the dataset


tips = sns.load_dataset('tips')
Loading Playground...
[Link](x="total_bill",
y="tip",
hue="time",
data=tips)

Output :
Example 3: using time and sex for determining the facet of the grid.

# importing the library


import seaborn as sns

# selecting style
[Link](style ="ticks")

# reading the dataset


tips = sns.load_dataset('tips')
Loading Playground...
[Link](x="total_bill",
y="tip",
hue="day",
col="time",
row="sex",
data=tips)

Output :
Example 4: using size attribute, we can see data points having different size.

# importing the library


import seaborn as sns

# selecting style
[Link](style ="ticks")

# reading the dataset


tips = sns.load_dataset('tips')
Loading Playground...
[Link](x="total_bill",
y="tip",
hue="day",
size="size",
data=tips)

Output :
Comment 09amit Follow 7

Article Tags: Computer Subject Machine Learning 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 for Machine Learning Machine Learning with R Machine Learning Algorithms EDA Math for Machine Learning Machine Learning Inte

Relational plots in Seaborn - Part II


Last Updated : 15 Jul, 2025

Prerequisite: Relational Plots in Seaborn - Part I


In the previous part of this article, we learnt about the relplot(). Now, we will be reading about the
other two relational plots, namely scatterplot() and lineplot() provided in seaborn library. Both these
plots can also be drawn with the help of kind parameter in relplot(). Basically relplot(), by default,
gives us scatterplot() only, and if we pass the parameter kind = "line", it gives us lineplot().
Example 1: Using relplot() to visualize tips dataset

import seaborn as sns


[Link](style ="ticks")

tips = sns.load_dataset('tips')
[Link](x ="total_bill", y ="tip", data = tips)

Output :

Example 2: Using relplot() with kind="scatter".

import seaborn as sns

[Link](style ="ticks")
tips = sns.load_dataset('tips')

[Link](x ="total_bill",
y ="tip", Loading Playground...
kind ="scatter",
data = tips)

Output :
Example 3: Using relplot() with kind="line".

import seaborn as sns

[Link](style ="ticks")
tips = sns.load_dataset('tips')

[Link](x ="total_bill",
y ="tip", Loading Playground...
kind ="line",
data = tips)

Output :

Though both these plots can be drawn using relplot(), seaborn also have separate functions for
visualizing these kind of plots. These functions do provides some other functionalities too, compared
to relplot(). Let us discuss about these function in more detail:

[Link]()
The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two
variables using a cloud of points, where each point represents an observation in the dataset. This
depiction allows the eye to infer a substantial amount of information about whether there is any
meaningful relationship between them.
Syntax :

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

Parameters :

Parameter Value Use

x, y numeric Input data variables

data Dataframe Dataset that is being used.

hue, size, name in data;


Grouping variable that will produce elements with different colors.
style optional

name, list, or dict;


palette Colors to use for the different levels of the hue variable.
optional

hue_order list; optional Specified order for the appearance of the hue variable levels.

tuple or
Normalization in data units for colormap applied to the hue variable
hue_norm Normalize object;
when it is numeric.
optional

list, dict, or tuple;


sizes determines the size of each point in the plot.
optional

size_order list; optional Specified order for appearance of the size variable levels

tuple or
Normalization in data units for scaling plot objects when the size
size_norm Normalize object;
variable is numeric.
optional

boolean, list, or
markers dictionary; object determining the shape of marker for each data points.
optional

style_order list; optional Specified order for appearance of the style variable levels

alpha float proportional opacity of the points.

If “brief”, numeric hue and size variables will be represented with a


“brief”, “full”, or
legend sample of evenly spaced values. If “full”, every group will get an entry
False; optional
in the legend. If False, no legend data is added and no legend is drawn.

matplotlib axes;
ax Axes object in which the plot is to be drawn.
optional

key, value Other keyword arguments are passed through to the underlying
kwargs
pairings plotting function.

Example 1: Plotting a scatterplot using marker to differentiate between timing of the people visiting
the restaurant.
import seaborn as sns

[Link](style ="ticks")
tips = sns.load_dataset('tips')
markers = {"Lunch": "s", "Dinner": "X"}

ax = [Link](x ="total_bill",
Loading Playground...
y ="tip",
style ="time",
markers = markers,
data = tips)

Output:

Example 2: Passing data vectors instead of names in a data frame.

import seaborn as sns

iris = sns.load_dataset("iris")

[Link](x = iris.sepal_length,
y = iris.sepal_width, Loading Playground...
hue = [Link],
style = [Link])

Output:

[Link]()
Scatter plots are highly effective, but there is no universally optimal type of visualization. For certain
datasets, you may want to consider changes as a function of time in one variable, or as a similarly
continuous variable. In this case, drawing a line-plot is a better option.
Syntax :
[Link](x=None, y=None, data=None, **kwargs)

Parameters :

Parameter Value Use

x, y numeric Input data variables

data Dataframe Dataset that is being used.

hue, size, Grouping variable that will produce elements with


name in data; optional
style different colors.

Colors to use for the different levels of the hue


palette name, list, or dict; optional
variable.

Specified order for the appearance of the hue


hue_order list; optional
variable levels.

Normalization in data units for colormap applied to


hue_norm tuple or Normalize object; optional
the hue variable when it is numeric.

sizes list, dict, or tuple; optional determines the size of each point in the plot.

Specified order for appearance of the size variable


size_order list; optional
levels

Normalization in data units for scaling plot objects


size_norm tuple or Normalize object; optional
when the size variable is numeric.

markers, object determining the shape of marker for each data


boolean, list, or dictionary; optional
dashes points.

Specified order for appearance of the style variable


style_order list; optional
levels

Grouping variable identifying sampling units. When


used, a separate line with correct terminology will be
units long_form_var drawn for each unit but no legend entry will be
inserted. Useful for displaying experimental replicate
distribution when exact identities are not necessary.

Method for aggregating the vector y at the same x


name of pandas method or callable
estimator point through multiple observations. If None, all
or None; optional
observations will be drawn.

Size of the confidence interval to be drawn when


ci int or "sd" or None; optional aggregating with an estimator. "sd" means drawing a
standard deviation.

Number of bootstraps to use for confidence interval


n_boot int; optional>
measurement.
Parameter Value Use

int, [Link], or
Seed or random number generator for reproducible
seed [Link];
bootstrapping.
optional

sort bool; optional is True, sorts the data.

Either using translucent error bands to display the


err_style "band" or "bars"; optional
confidence intervals or discrete error bars.

Additional parameters to control the aesthetics of


err_kws dict of keyword arguments
the error bars.

If “brief”, numeric hue and size variables will be


represented with a sample of evenly spaced values.
legend “brief”, “full”, or False; optional If “full”, every group will get an entry in the legend. If
False, no legend data is added and no legend is
drawn.

ax matplotlib axes; optional Axes object in which the plot is to be drawn.

Other keyword arguments are passed through to the


kwargs key, value pairings
underlying plotting function.

Example 1: Basic visualization of "fmri" dataset using lineplot()

import seaborn as sns

[Link](style = 'whitegrid')
fmri = sns.load_dataset("fmri")

[Link](x ="timepoint", Loading Playground...


y ="signal",
data = fmri)

Output :

Example 2: Grouping data points on the basis of category, here as region and event.

import seaborn as sns

[Link](style = 'whitegrid')
fmri = sns.load_dataset("fmri")

[Link](x ="timepoint",
y ="signal", Loading Playground...
hue ="region",
style ="event",
data = fmri)

Output :

Example 3: A complex plot visualizing "dots" dataset, to show the power of seaborn. Here, in this
example, quantitative color mapping is used.

import seaborn as sns

[Link](style = 'whitegrid')
dots = sns.load_dataset("dots").query("align == 'dots'")

[Link](x ="time",
y ="firing_rate", Loading Playground...
hue ="coherence",
style ="choice",
data = dots)

Output :

Comment 09amit Follow 2


Article Tags: Computer Subject Machine Learning 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

Scatterplot using Seaborn in Python


Last Updated : 27 May, 2025

Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides
beautiful default styles and color palettes to make statistical plots more attractive. It is built on the
top of matplotlib library and also closely integrated into the data structures from pandas.

What is a scatterplot?
A scatter plot displays points on a two-dimensional axis to show the relationship between two
variables. Each dot represents an observation from your dataset. With Seaborn’s scatterplot()
function, you can easily:

Show relationships
Differentiate groups using hue (color), style (marker) and size (point radius)
Improve accessibility and clarity with semantic mapping

Syntax

[Link](
x=None, y=None,
hue=None, style=None, size=None,
data=None, palette=None,
legend='brief', alpha='auto',
**kwargs
)

Parameters:

Parameter Description

x, y Numeric variables for the X and Y axes

data Pandas DataFrame

hue Variable that maps to different colors

style Variable that maps to different marker shapes

size Variable that maps to different marker sizes


Parameter Description

palette Defines the color palette

alpha Transparency of points

legend Controls legend visibility and behavior

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

Examples
Example 1: In this example, we are creating a basic scatter plot with the FMRI dataset. We plot the
timepoint on the x-axis and the signal on the y-axis to observe how the signal changes over time.

import seaborn as sns


import [Link] as plt

[Link](style='whitegrid')
fmri = sns.load_dataset("fmri")

[Link](x="timepoint", y="signal", data=fmri)


[Link]("FMRI Signal Over Time")
[Link]()

Output

Using [Link]()

Explanation: [Link](style='whitegrid') sets a clean plot style with gridlines.


sns.load_dataset("fmri") loads brain signal data over time. [Link](x="timepoint",
y="signal", data=fmri) creates a scatter plot showing how FMRI signals vary with time.

Example 2: In this example, we extend the basic FMRI scatter plot by adding color (hue) based on
the region and different markers (style) based on the event.

[Link](
x="timepoint", y="signal",
hue="region", style="event",
data=fmri
)
[Link]("FMRI Signal by Region and Event")
[Link]()
Output

Using [Link]()

Explanation: [Link](x="timepoint", y="signal", hue="region", style="event", data=fmri)


creates a scatter plot of FMRI signals over time, using different colors for regions and marker styles
for events.

Example 3: In this example, we use the Tips dataset to create a scatter plot showing how tips vary
across different days of the week. The day is plotted on the x-axis and the tip amount on the y-axis.

tips = sns.load_dataset("tips")
[Link](x="day", y="tip", data=tips)
[Link]("Tips by Day")
[Link]()

Output

Using [Link]()

Explanation: sns.load_dataset("tips") loads a dataset containing restaurant tipping data.


[Link](x="day", y="tip", data=tips) creates a scatter plot showing tip amounts given on
different days.

Grouping variables in Seaborn Scatter Plot with different attributes


1. Adding the marker attributes: The circle is used to represent the data point and the default
marker here is a blue circle. In the above output, we are seeing the default output for the marker, but
we can customize this blue circle with marker attributes.

[Link](x='day', y='tip', data= tip, marker = '+')

Output
2. Adding the hue attributes: It will produce data points with different colors. Hue can be used to
group to multiple data variable and show the dependency of the passed data values are to be
plotted.

Syntax: [Link]( x, y, data, hue)

[Link](x='day', y='tip', data=tip, hue='time')

Output

In the above example, we can see how the tip and day bill is related to whether it was lunchtime or
dinner time. The blue color has represented the Dinner and the orange color represents the Lunch.

Let's check for a hue = " day "

[Link](x='day', y='tip', data=tip, hue='day')

3. Adding the style attributes: Grouping variable that will produce points with different markers.
Using style we can generate the scatter grouping variable that will produce points with different
markers.

Syntax: [Link]( x, y, data, style)

[Link](x='day', y='tip', data=tip, hue="time", style="time")

Output
4. Adding the palette attributes: Using the palette we can generate the point with different colors.
In this below example we can see the palette can be responsible for a generate the scatter plot with
different colormap values.

Syntax: [Link]( x, y, data, palette="color_name")

[Link](x='day', y='tip', data=tip, hue='time', palette='pastel')

Output

5. Adding size attributes: Using size we can generate the point and we can produce points with
different sizes.

Syntax: [Link]( x, y, data, size)

[Link](x='day', y='tip', data=tip ,hue='size', size = "size")

Output

6. Adding legend attributes: We can control the legend display using the legend parameter:
legend='full' shows all groups, legend='brief' shows a sample for numeric variables, and
legend=False hides the legend completely.

Syntax: [Link]( x, y, data, legend=''brief)

[Link](x='day', y='tip', data=tip, hue='day',


sizes=(30, 200), legend='brief')

Output
7. Adding alpha attributes: Using alpha we can control proportional opacity of the points. We can
decrease and increase the opacity.

Syntax: [Link]( x, y, data, alpha="0.2")

[Link](x='day', y='tip', data=tip, alpha = 0.1)

Output

Comment N nishan… Follow 6

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

Visualizing Relationship between variables with scatter plots in


Seaborn
Last Updated : 15 Jul, 2025

To understand how variables in a dataset are related to one another and how that relationship is
dependent on other variables, we perform statistical analysis. This Statistical analysis helps to
visualize the trends and identify various patterns in the dataset. One of the functions which can be
used to get the relationship between two variables in Seaborn is relplot().
Relplot() combines FacetGrid with either of the two axes-level functions scatterplot() and lineplot().
Scatterplot is default kind of relplot(). Using this we can visualize joint distribution of two variables
through a cloud of points. We can draw scatterplot in seaborn using various ways. The most common
one is when both the variables are numeric.
Example: Let's take an example of a dataset that consists a data of CO2 emissions of different
vehicles. To get the dataset click here.

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

# set grid style


[Link](style ="darkgrid")

# import dataset
dataset = pd.read_csv('[Link]')

Let's plot the basic scatterplot for visualizing the relation between the target variable
"CO2EMISSIOnS" and "ENGINE SIZE"
[Link](x ="ENGINESIZE", y ="CO2EMISSIONS",
data = dataset);

Output:

We can add visualize one more variable by adding another dimension to the plot. This can be done
by using "hue", which colors the points of the third variable, thus adding a meaning to it.
[Link](x ="ENGINESIZE", y ="CO2EMISSIONS",
hue ="FUELTYPE", data = dataset);

Output:

To highlight the different classes, we can add marker styles


[Link](x ="ENGINESIZE", y ="CO2EMISSIONS",
hue ="FUELTYPE", style ="FUELTYPE",
data = dataset);

Output:

In the previous example, hue semantic was for a categorical variable, so it had a default qualitative
palette. But if we use a numerical variable instead of categorical, then the default palette used is
sequential, which can be modified too.
[Link](x ="ENGINESIZE", y ="CO2EMISSIONS",
hue ="CYLINDERS", data = dataset);

Output:
We can also change the size of points for the third variable.
[Link](x ="ENGINESIZE", y ="CO2EMISSIONS",
size ="CYLINDERS", data = dataset);

Output:

Comment D devans… Follow 5

Article Tags: Python Data Visualization 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

How To Make Scatter Plot with Regression Line using Seaborn in


Python?
Last Updated : 23 Jul, 2025

In this article, we will learn how to make scatter plots with regression lines using Seaborn in Python.
Let's discuss some concepts :

Seaborn : Seaborn is a tremendous visualization library for statistical graphics plotting in Python.
It provides beautiful default styles and color palettes to make statistical plots more attractive. It is
built on the highest of matplotlib library and also closely integrated to the info structures from
pandas.
Scatter Plot : Scatter plots are wont to observe the relationship between variables and uses dots
to represent the connection between them. The scatter() method within the matplotlib library is
employed to draw a scatter plot. Scatter plots are widely wont to represent relationships among
variables and the way change in one affects the opposite.
Regression Plot : Two main functions in seaborn are wont to visualize a linear relationship as
determined through regression. These functions, regplot() and lmplot() are closely related and
share much of their core functionality.

Adding a regression curve to a scatterplot between two numerical variables is a good way to
ascertain the linear trend. And we also will see an example of customizing the scatter plot with a
regression curve.

Steps Required

Import Library (Seaborn)


Import or load or create data.
Plot the graph with the help of regplot() or lmplot() method.

Example 1: Using regplot() method

This method is used to plot data and a linear regression model fit. There are a number of mutually
exclusive options for estimating the regression model.

# importing libraries
import seaborn as sb

# load data
df = sb.load_dataset('iris')

# use regplot
[Link](x = "sepal_length",
y = "petal_length",
ci = None,
data = df)
Output :

Example 2: Using lmplot() method

The lmplot is another most basic plot. It shows a line representing a linear regression model along
with data points on the 2D-space and x and y can be set as the horizontal and vertical labels
respectively.

# importing libraries
import seaborn as sb

# load data
df = sb.load_dataset('iris')

# use lmplot
[Link](x = "sepal_length",
y = "petal_length",
ci = None,
data = df)

Output :
Comment D deepa… Follow 5

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

Scatter Plot with Marginal Histograms in Python with Seaborn


Last Updated : 23 Jul, 2025

Prerequisites: Seaborn
Scatter Plot with Marginal Histograms is basically a joint distribution plot with the marginal
distributions of the two variables. In data visualization, we often plot the joint behavior of two
random variables (bi-variate distribution) or any number of random variables. But if data is too large,
overlapping can be an issue. Hence, to distinguish between variables it is useful to have the
probability distribution of each variable on the side along with the joint plot. This individual
probability distribution of a random variable is referred to as its marginal probability distribution.
In seaborn, this is facilitated with jointplot(). It represents the bi-variate distribution using
scatterplot() and the marginal distributions using histplot().

Approach

Import seaborn library


Load dataset of your choice
Use jointplot() on variables of your dataset

Example 1:

# importing and creating alias for seaborn


import seaborn as sns

# loading tips dataset


tips = sns.load_dataset("tips")

# plotting scatterplot with histograms for features total bill and tip.
[Link](data=tips, x="total_bill", y="tip")

Output :
<[Link] at 0x26203152688>

jointplot_with_histograms

Example 2: Using kind=”reg” attribute you can add a linear regression fit and univariate KDE curves.
import seaborn as sns

tips = sns.load_dataset("tips")

# here "*" is used as a marker for scatterplot


[Link](data=tips, x="total_bill", y="tip", kind="reg", marker="*")

Output :

scatterplot with a linear regression fit

Example3: To add conditional colors to the scatterplot you can use hue attribute but it draws
separate density curves (using kdeplot()) on the marginal axes.

import seaborn as sns

tips = sns.load_dataset("tips")

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

Output :

scatterplot3

Comment T tejalka… Follow 5

Article Tags: Python Python-Seaborn

Company Explore Tutorials Courses Offline Preparation


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

[Link]() method in Python


Last Updated : 15 Jul, 2025

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface
for drawing attractive and informative statistical graphics. The colors stand out, the layers blend
nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic
quality, but it provides meaningful insights to us as well.

[Link]()
Draw a line plot with the possibility of several semantic groupings. The relationship between x and y
can be shown for different subsets of the data using the hue, size, and style parameters. These
parameters control what visual semantics are used to identify the different subsets. It is possible to
show up to three dimensions independently by using all three semantic types, but this style of plot
can be hard to interpret and is often ineffective. Using redundant semantics (i.e. both hue and style
for the same variable) can be helpful for making graphics more accessible.

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.

Below is the implementation of above method with some examples :


Example 1:

# importing packages
import seaborn as sns
import [Link] as plt

# loading dataset
data = sns.load_dataset("iris")

# draw lineplot
[Link](x="sepal_length", y="sepal_width", data=data)
[Link]()

Output :

Example 2 :

# importing packages
import seaborn as sns
import [Link] as plt

# loading dataset
data = sns.load_dataset("tips")

# draw lineplot
# hue by sex
# style to hue
[Link](x="total_bill", y="size",
hue="sex", style="sex",
data=data)

[Link]()

Output :
Comment D deepa… Follow 3

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

Creating A Time Series Plot With Seaborn And Pandas


Last Updated : 11 Dec, 2020

In this article, we will learn how to create A Time Series Plot With Seaborn And Pandas. Let's
discuss some concepts :
Pandas is an open-source library that's built on top of NumPy library. It's a Python package that
gives various data structures and operations for manipulating numerical data and statistics. It's
mainly popular for importing and analyzing data much easier. Pandas is fast and it's high-
performance & productive for users.
Seaborn is a tremendous visualization library for statistical graphics plotting in Python. It provides
beautiful default styles and color palettes to form statistical plots more attractive. It's built on the
highest of matplotlib library and also closely integrated to the info structures from pandas.
A timeplot (sometimes called a statistic graph) displays values against the clock. They're almost
like x-y graphs, but while an x-y graph can plot a spread of “x” variables (for example, height,
weight, age), timeplots can only display time on the x-axis. Unlike the pie charts and bar charts,
these plots don't have categories. Timeplots are good for showing how data changes over time.
For instance, this sort of chart would work well if you were sampling data randomly times.

Steps Needed

1. Import packages
2. Import / Load / Create data.
3. Plot the time series plot over data using lineplot (as tsplot was replaced with lineplot since Sep
2020).

Examples

Here, we create a rough data for understanding the time series plot with the help of some examples.
Let's create the data :

# importing packages
import pandas as pd

# creating data
df = [Link]({'Date': ['2019-10-01', '2019-11-01',
'2019-12-01','2020-01-01',
'2020-02-01', '2020-03-01',
'2020-04-01', '2020-05-01',
'2020-06-01'],

'Col_1': [34, 43, 14, 15,


15, 14, 31, 25, 62],

'Col_2': [52, 66, 78, 15, 15,


5, 25, 25, 86],

'Col_3': [13, 73, 82, 58, 52,


87, 26, 5, 56],

'Col_4': [44, 75, 26, 15, 15,


14, 54, 25, 24]})

# view dataset
display(df)

Output:

Example 1: Simple time series plot with single column using lineplot

# importing packages
import seaborn as sns
import pandas as pd

# creating data
df = [Link]({'Date': ['2019-10-01', '2019-11-01',
'2019-12-01','2020-01-01',
'2020-02-01', '2020-03-01',
'2020-04-01', '2020-05-01',
'2020-06-01'],

'Col_1': [34, 43, 14, 15, 15,


14, 31, 25, 62],

'Col_2': [52, 66, 78, 15, 15,


5, 25, 25, 86],

'Col_3': [13, 73, 82, 58, 52,


87, 26, 5, 56],
'Col_4': [44, 75, 26, 15, 15,
14, 54, 25, 24]})

# create the time series plot


[Link](x = "Date", y = "Col_1",
data = df)

[Link](rotation = 25)

Output :
Example 2: (Simple time series plot with multiple columns using line plot)

# importing packages
import seaborn as sns
import pandas as pd

# creating data
df = [Link]({'Date': ['2019-10-01', '2019-11-01',
'2019-12-01','2020-01-01',
'2020-02-01', '2020-03-01',
'2020-04-01', '2020-05-01',
'2020-06-01'],

'Col_1': [34, 43, 14, 15, 15,


14, 31, 25, 62],

'Col_2': [52, 66, 78, 15, 15,


5, 25, 25, 86],

'Col_3': [13, 73, 82, 58, 52,


87, 26, 5, 56],
'Col_4': [44, 75, 26, 15, 15,
14, 54, 25, 24]})

# create the time series plot


[Link](x = "Date", y = "Col_1", data = df)
[Link](x = "Date", y = "Col_2", data = df)
[Link]("Col_1 and Col_2")
[Link](rotation = 25)

Output :
Example 3: Multiple time series plot with multiple columns

# importing packages
import seaborn as sns
import pandas as pd
import [Link] as plt

# creating data
df = [Link]({'Date': ['2019-10-01', '2019-11-01',
'2019-12-01','2020-01-01',
'2020-02-01', '2020-03-01',
'2020-04-01', '2020-05-01',
'2020-06-01'],

'Col_1': [34, 43, 14, 15, 15,


14, 31, 25, 62],

'Col_2': [52, 66, 78, 15, 15,


5, 25, 25, 86],

'Col_3': [13, 73, 82, 58, 52,


87, 26, 5, 56],
'Col_4': [44, 75, 26, 15, 15,
14, 54, 25, 24]})
# create the time series subplots
fig,ax = [Link]( 2, 2,
figsize = ( 10, 8))

[Link]( x = "Date", y = "Col_1",


color = 'r', data = df,
ax = ax[0][0])

ax[0][0].tick_params(labelrotation = 25)
[Link]( x = "Date", y = "Col_2",
color = 'g', data = df,
ax = ax[0][1])

ax[0][1].tick_params(labelrotation = 25)
[Link](x = "Date", y = "Col_3",
color = 'b', data = df,
ax = ax[1][0])

ax[1][0].tick_params(labelrotation = 25)

[Link](x = "Date", y = "Col_4",


color = 'y', data = df,
ax = ax[1][1])

ax[1][1].tick_params(labelrotation = 25)
fig.tight_layout(pad = 1.2)
Output :

Comment D deepa… Follow 7

Article Tags: Python Python-pandas 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 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

Barplot using seaborn in Python


Last Updated : 15 Jul, 2025

Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides
beautiful default styles and color palettes to make statistical plots more attractive. It is built on the
top of matplotlib library and also closely integrated to the data structures from pandas.

[Link]()

[Link]() method is used to draw a barplot. A bar plot 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, order=None,


hue_order=None, estimator=<function mean at 0x7fa4c4f67940>, ci=95, n_boot=1000,
units=None, seed=None, orient=None, color=None, palette=None, saturation=0.75,
errcolor='.26', errwidth=None, capsize=None, 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, 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.

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

Grouping variables in Seaborn barplot with different attributes

Example 1: Draw a set of vertical bar plots grouped by a categorical variable.


Creating a simple bar plot using seaborn.
Syntax:
[Link]( x, y, data)

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

# class v / s fare barplot


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

# Show the plot


[Link]()

Output :

Example 2: Draw a set of vertical bars with nested grouping by two variables.
Creating a bar plot using hue parameter with two variables.
Syntax:

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

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')
# class v / s fare barplot
[Link](x = 'class', y = 'fare', hue = 'sex', data = df)

# Show the plot


[Link]()

Output :

Example 3: shows a Horizontal barplot.


exchange the data variable instead of two data variables then it means that the axis denotes each of
these data variables as an axis.
X denotes an x-axis and y denote a y-axis.

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

# fare v / s class horizontal barplot


[Link](x = 'fare', y = 'class', hue = 'sex', data = df)

# Show the plot


[Link]()

Output :
Example 4: Plot all bars in a given order.
Control barplot order by passing an explicit order.

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

# class v / s fare barplot in given order


[Link](x = 'class', y = 'fare', data = df,
order = ["Third", "Second", "First"])

# Show the plot


[Link]()

Output :
Example 5: Plot all bars in a single color using color attributes.
Color for all of the elements.
Syntax:

[Link]( x, y, data, color)

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file from seaborn library


df = sns.load_dataset('titanic')

# class v / s fare barplot with same colour


[Link](x = 'class', y = 'fare', data = df, color = "salmon")

# Show the plot


[Link]()

Output :
Example 6: barplot without error bars using ci attributes.
We will use None it means no bootstrapping will be performed, and error bars will not be drawn

Syntax:

[Link]( x, y, data, ci)

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

# class v / s fare barplot


# without error bars
[Link](x = 'class', y = 'fare', data = df, ci = None)

# Show the plot


[Link]()

Output :
Example 7: Colors to use for the different levels of the hue variable using palette.
Using the palette we can generate the point with different colors. In this below example we can see
the palette can be responsible for a generate the barplot with different colormap values.

Syntax:

[Link]( x, y, data, palette=”color_name”)

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

[Link](x = 'class', y = 'fare',


hue = 'sex', data = df, palette='pastel')

# Show the plot


[Link]()

Output:
Possible values of palette are:

Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap,
CMRmap_r, Dark2, Dark2_r,

GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn,
PRGn_r, Paired, Paired_r,

Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr,
PuOr_r, PuRd, PuRd_r,

Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn,
RdYlGn_r, Reds, Reds_r, Set1,

Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu,
YlGnBu_r, YlGn_r, YlOrBr,

YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone,
bone_r, brg, brg_r, bwr, bwr_r,

cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r,
flag, flag_r, gist_earth,

gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow,


gist_rainbow_r, gist_stern,

Example 8: Using the statistical function [Link] and [Link] to estimate within
each categorical bin.

# importing the required library


import seaborn as sns
from numpy import median
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

[Link](x = 'class', y = 'fare', hue = 'sex', data = df, estimator=median)

# Show the plot


[Link]()

Output:

For [Link]:

from numpy import mean


[Link](x = 'class', y = 'fare', hue = 'sex', data = df, estimator=mean)

Output:

Example 9: Using the saturation parameter.


The 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.
Syntax:

[Link]( x, y, data, saturation)

# importing the required library


import seaborn as sns
import [Link] as plt
# read a [Link] file
# from seaborn library
df = sns.load_dataset('titanic')

[Link](x = 'class', y = 'fare', hue = 'sex', data = df,saturation = 0.1)

# Show the plot


[Link]()

Output:

Example 10: Use [Link]() parameters to control the style.


We can set Width of the gray lines that frame the plot elements using linewidth. Whenever we
increase linewidth than the point also will increase automatically.
Syntax:

[Link](x, y, data, linewidth, edgecolor)

# importing the required library


import seaborn as sns
import [Link] as plt

# read a [Link] file


# from seaborn library
df = sns.load_dataset('titanic')

[Link](x="class", y="fare", data=df,


linewidth=2.5, facecolor=(1, 1, 1, 0),
errcolor=".2", edgecolor=".2")

Output:
Comment A ankthon Follow 7

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

[Link]() in Python
Last Updated : 15 Jul, 2025

[Link]() is a function in the Seaborn library in Python used to display the counts of
observations in categorical data. It shows the distribution of a single categorical variable or the
relationship between two categorical variables by creating a bar plot. Example:

import seaborn as sns


import [Link] as plt

# read a [Link] file from seaborn library


df = sns.load_dataset('tips')

# count plot on single categorical variable


[Link](x ='sex', data = df)

[Link]()

Output :

single categorical variable

Explanation: This code creates a count plot using Seaborn to display the frequency of male and
female individuals in the sex column of the "tips" dataset. It uses [Link]() to plot the data
and [Link]() to display the plot.

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:

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]().

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

Examples of [Link]()

Example 1: Show value counts for two categorical variables and using hue parameter

This code demonstrates how to create a count plot using Seaborn in Python to visualize the
distribution of categorical data. We are using the "tips" dataset from Seaborn, and the plot visualizes
the frequency of male and female customers (sex) while distinguishing between smokers and non-
smokers using the hue parameter.

import seaborn as sns


import [Link] as plt

# read a [Link] file from seaborn library


df = sns.load_dataset('tips')

# count plot on two categorical variable


[Link](x ='sex', hue = "smoker", data = df)

[Link]()

Output:

two categorical variables and using hue parameter

Explanation: In this code, [Link]() is used to create a count plot where the x-axis represents
the sex column, and the hue parameter splits the data by smoker status. The [Link]() function
renders the plot, displaying the distribution of male and female customers as well as how many of
them smoke or don't smoke.

Example 2: Plot the bars horizontally

This code demonstrates how to create a count plot using Seaborn in Python with the "tips" dataset.
Unlike the standard vertical count plot, this code uses the y parameter to plot the categorical
variable (sex) on the y-axis.

import seaborn as sns


import [Link] as plt

# read a [Link] file from seaborn library


df = sns.load_dataset('tips')

# count plot along y axis


[Link](y ='sex', hue = "smoker", data = df)

[Link]()

Output:
horizontal bars

Explanation: In this code, [Link]() is used with the y parameter to create a horizontal count
plot. The y-axis represents the sex column, while the hue parameter divides the data based on
whether the customers are smokers or not. The [Link]() function displays the plot, allowing us to
compare the number of male and female customers who smoke versus those who do not.

Example 3: Use different color palette attributes

This code shows how to use a custom color palette in a Seaborn count plot. The "tips" dataset is
loaded using Seaborn, and the count plot visualizes the distribution of male and female customers
(sex). By using the palette parameter with the "Set2" palette, we change the default colors of the
plot to create a visually appealing and distinguishable chart.

import seaborn as sns


import [Link] as plt

# read a [Link] file from seaborn library


df = sns.load_dataset('tips')

# use a different colour palette in count plot


[Link](x ='sex', data = df, palette = "Set2")

[Link]()

Output:
color palette attributes

Explanation: In this code, [Link]() is used to create a vertical bar plot of the sex column from
the "tips" dataset. The palette parameter is set to "Set2", which is a predefined Seaborn color
palette, to style the plot with a specific set of colors. The plot displays the count of male and female
customers, and [Link]() is used to render the plot.

Possible values of palette are:


Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap,
CMRmap_r, Dark2, Dark2_r,
GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn,
PRGn_r, Paired, Paired_r,
Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr,
PuOr_r, PuRd, PuRd_r,
Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn,
RdYlGn_r, Reds, Reds_r, Set1,
Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu,
YlGnBu_r, YlGn_r, YlOrBr,
YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone,
bone_r, brg, brg_r, bwr, bwr_r,
cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r,
flag, flag_r, gist_earth,
gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow,
gist_rainbow_r, gist_stern,

Example 4: using a color parameter in the plot.

This code demonstrates how to create a count plot using Seaborn to visualize the distribution of
passengers by class in the Titanic dataset. The plot also differentiates between male and female
passengers using the hue parameter.
import seaborn as sns
import [Link] as plt

# Load the Titanic dataset from seaborn library


df = sns.load_dataset('titanic')

[Link](x='class', hue='sex', data=df, color="salmon")

[Link]()

Output:

color parameter

Explanation: In this code, [Link]() is used to create a count plot that shows the number of
passengers in each class (class) from the Titanic dataset. The hue parameter is set to 'sex', which
splits the bars based on male and female passengers. The color parameter is set to "salmon" to
change the bar colors. The [Link]() function displays the resulting plot.

Example 5: Using a saturation parameter in the plot.

This code demonstrates how to create a count plot using Seaborn, visualizing the distribution of
male and female passengers from the Titanic dataset. The color parameter is set to "salmon", and
the saturation is adjusted to 0.1 for a lighter color tone.

import seaborn as sns


import [Link] as plt

# read a [Link] file from seaborn library


df = sns.load_dataset('titanic')

# class v / s fare barplot


[Link](x ='sex', data = df, color="salmon", saturation = 0.1)
[Link]()

Output:
Explanation: In this code, the [Link]() function is used to create a count plot showing the
number of male and female passengers (sex) from the Titanic dataset. The color parameter is set to
"salmon" to color the bars. The saturation parameter is set to 0.1, which reduces the intensity of the
color, making it lighter. The [Link]() function is called to display the plot.

Example 6: Use [Link]() parameters to control the style.

This code demonstrates how to create a count plot using Seaborn for the 'sex' column in the Titanic
dataset. Custom edge colors and transparency are applied to the bars, enhancing the plot's visual
appearance.

import seaborn as sns


import [Link] as plt

# Load the Titanic dataset from Seaborn


df = sns.load_dataset('titanic')

# Create a countplot for 'sex' with custom edge colors and transparency
[Link](
x='sex',
data=df,
color="salmon",
facecolor=(0, 0, 0, 0),
linewidth=5,
edgecolor=sns.color_palette("BrBG", 2)
)

[Link]()

Output:
Explanation: In this code, the [Link]() function is used to create a count plot for the 'sex'
column in the Titanic dataset. The color parameter is set to "salmon", while facecolor=(0, 0, 0, 0)
makes the bars transparent. The linewidth is set to 5, making the edges thicker. The edgecolor is
customized using a color palette ("BrBG", 2) for a distinct visual appeal. Finally, [Link]() displays
the plot.

Colormap Possible values are:


Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r,
CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r,
OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r,
Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd,
PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r,
RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral,

Comment A ankthon Follow 11

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

Boxplot using Seaborn in Python


Last Updated : 15 Jul, 2025

Boxplot is used to see the distribution of numerical data and identify key stats like minimum and
maximum values, median, identifying outliers, understanding how data is distributed and can
compare the distribution of data across different categories or variables. In Seaborn the
[Link]() function is used to plot it and in this article we will learn about it.

Lets see a example: We will use the tips dataset which is an inbuilt dataset. This dataset contains
information about restaurant tips, total bill amount, tip amount, customer details like sex and day of
the week etc. Also we will be using Seaborn and Matplotlib libraries for this.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
[Link](x="day", y="tip", data=df)
[Link]()

Output:

Syntax:

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


linewidth=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 Axes object with the plot drawn on it.

Example 1: Horizontal Boxplot of Total Bill

By changing the axis to x, we can plot distribution of the total bill in a horizontal format. This makes
it easy to view data horizontally.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
[Link](x=df["total_bill"])
[Link]()

Output:

Horizontal boxplot

Example 2: Boxplot with Hue

We will use hue parameter to color-code the boxplots based on the smoker status. This makes it
easier to get a difference between smokers and non-smokers.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
[Link](x="day", y="total_bill", hue="smoker", data=df)
[Link]()

Output:
Boxplot with Hue

Example 3: Custom Colors Palette

We use hue and palette parameters to color-code the boxplot based on gender. This helps in
making the difference between male and female customers. We will define a custom color palette as
skyblue and lightpink for male and female respectively.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
palette = {'Male': 'skyblue', 'Female': 'lightpink'}
[Link](x="day", y="tip", hue="sex", data=df, palette=palette)
[Link]()

Output:

Custom Colors with Palette


Example 4: Increase Outline Thickness

The linewidth parameter controls thickness of the boxplot lines. By increasing it plot’s boundaries
become more thick.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
[Link](x="day", y="tip", data=df, linewidth=2)
[Link]()

Output:

Boxplot with linewidth=2

Example 5: Horizontal Boxplot for Multiple Columns

In this example we plot multiple variables horizontally by setting the orient parameter to "h". This
helps in comparing distributions of multiple numerical columns.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
[Link](data=df[["total_bill", "tip", "size"]], orient="h")
[Link]()

Output:
Horizontal Boxplot for Multiple Columns

Example 6: Set Single Color

We can use color parameter to set a single color for the entire boxplot which ensures a uniform
color.

import seaborn as sns


import [Link] as plt

df = sns.load_dataset("tips")
[Link](x="day", y="tip", data=df, color="green")
[Link]()

Output:

Single Color

With Seaborn's boxplot() we can easily visualize and compare data distributions which helps us to
gain valuable insights into our dataset in a clear and effective manner.
Comment N nishan… Follow 5

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

You might also like