Numpy 2
Numpy 2
Tutorials
Practice V
Jobs
Python Tutorial Data Types Interview Questions Examples Quizzes DSA Python Data Science NumPy Pandas Practice
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:
Syntax
[Link](scale=1.0, size=None)
Parameters:
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
Explanation
scale=1.5 moderate spread.
size=5 returns 5 values.
arr stores the array like [0.21, 1.33, 0.94, ...].
import numpy as np
import [Link] as plt
import seaborn as sns
s = 2 # scale
n = 800 # number of points
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.
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
Syntax
[Link](df, size=None)
Parameters:
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
import numpy as np
x = [Link](5, size=4)
print(x)
Loading Playground...
Output
import numpy as np
m = [Link](3, size=(2, 3))
print(m)
Loading Playground...
Output
import numpy as np
import [Link] as plt
from [Link] import chi2
df = 2
size = 1000
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.
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.
Examples of Vectorization
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]
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]
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]
import numpy as np
a1 = [Link]([10, 20, 30])
res = a1 > 15
print(res)
Loading Playground...
Output
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]]
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.
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.
Example: We will create a large NumPy array and apply the same operation (multiply each element
by 2) using both:
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]()
Output
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:
import numpy as np
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.
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:
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]
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]
This example checks each age in the array and assigns "Adult" or "Minor" using [Link]().
import numpy as np
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.
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.
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.
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
Output
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
Output
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.
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.
import numpy as np
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.
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
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.
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.
The [Link] module provides several formats for storing sparse matrices, each optimized for
different operations:
csr_matrix Fast row slicing, math Compressed Sparse Row good for arithmetic and row
operations access.
coo_matrix Easy matrix building Coordinate format using (row, col, value) triples.
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
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().
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.
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]]
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
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
print([Link]())
Output
[[0. 0. 3. 0. 4.]
[0. 0. 5. 7. 0.]
[0. 0. 0. 0. 0.]
[0. 2. 6. 0. 0.]]
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
Output
[[3 0 0 0 0]
[0 5 0 0 0]
[0 0 6 0 0]
[0 0 0 7 0]]
Related Articles:
Compressed Sparse formats CSR and CSC in Python
Python program to Convert a Matrix to Sparse Matrix
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:
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.
img = [Link]("[Link]")
print("Shape:", [Link])
print("Data type:", [Link]) Loading Playground...
Output
Explanation: Shape helps understand the image layout (e.g., 266x341x3 for RGB). Data type
(usually uint8) shows pixel value range (0-255).
RAW saved
Explanation: tofile() saves the image pixel data as a binary file, useful for low-level image
processing.
orig = [Link]("[Link]")
h, w, c = [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).
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.
img = [Link]("[Link]")
x, y, _ = [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.
img = [Link]("[Link]")
flipped = [Link](img)
[Link](flipped)
[Link]('off') Loading Playground...
[Link]("Flipped Image (Up-Down)")
[Link]()
Output
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.
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.
Sharpening increases contrast between edges to enhance details and clarity. Unsharp masking
subtracts a blurred version from the original.
img = [Link]("[Link]")
if [Link][-1] == 4:
img = rgba2rgb(img)
[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)
[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.
Explanation: Smooths the image using a Gaussian kernel to reduce high-frequency noise while
preserving structure.
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
[Link](im, cmap='gray')
[Link]('off')
Loading Playground...
[Link]("Original Synthetic Image")
[Link]()
[Link](sobel_edges, cmap='gray')
[Link]('off')
[Link]("Sobel Edge Detection")
[Link]()
Output
Original Synthetic Image
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:
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.
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.
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.
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")
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")
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.
[Link](style="dark")
fmri = sns.load_dataset("fmri")
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.
[Link](style="ticks")
Output
Related Articles:
Maplotlib Library
Pandas
Comment 09amit Follow 17
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
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.
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
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.
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:
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.
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.
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...
[Link]()
Output:
Explanation:
Seaborn’s [Link]() creates a line plot from a DataFrame.
Matplotlib functions customize the title, axis labels and grid styling.
import numpy as np
import [Link] as plt
import seaborn as sns
[Link](figsize=(8, 5))
Output:
Explanation:
[Link]() creates a smooth sine wave.
[Link]() overlays red data points for better visualization.
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')
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.
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.
# make a countplot
[Link](x ='sex', data = tips)
Output:
tips = sns.load_dataset('tips')
sns.set_style('ticks')
[Link](x ='sex', data = tips, palette = 'deep')
Output:
# make a countplot
[Link](x ='sex', data = tips)
Output:
# make a countplot
[Link](x ='sex', data = tips)
Output:
tips = sns.load_dataset('tips')
[Link](x ='sex', data = tips)
[Link]()
Output
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.
tips = sns.load_dataset('tips')
[Link](x ='total_bill', y ='tip', size = 2, aspect = 4, data = tips)
Loading Playground...
Output:
poster
paper
notebook
talk
tips = sns.load_dataset('tips')
sns.set_context('poster', font_scale = 2)
[Link](x ='sex', data = tips, palette ='coolwarm')
Loading Playground...
Output:
tips = sns.load_dataset('tips')
sns.set_context('paper', font_scale = 2)
[Link](x ='sex', data = tips, palette = 'coolwarm')
Output:
tips = sns.load_dataset('tips')
sns.set_context('notebook', font_scale = 2)
[Link](x ='sex', data = tips, palette ='coolwarm')
Output:
Example 4: Using talk.
tips = sns.load_dataset('tips')
sns.set_context('talk', font_scale = 2)
[Link](x ='sex', data = tips, palette ='coolwarm')
Output:
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:
[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:
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.
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.
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.
[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.
[Link](sns.color_palette("terrain_r", 7))
[Link]()
Output:
import pandas as pd
import seaborn as sns
[Link](sns.color_palette("deep", 10))
Output:
import pandas as pd
import seaborn as sns
[Link](sns.color_palette("muted", 10))
Output:
import pandas as pd
import seaborn as sns
[Link](sns.color_palette("bright", 10))
Output:
import pandas as pd
import seaborn as sns
[Link](sns.color_palette("dark", 10))
Output:
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
Output:
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] uses many arguments as input, main of which are described below in form of
table:
Value
Argument
Description
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
Output :
Example 2:
# importing packages
import seaborn
import [Link] as plt
Example 3:
# importing packages
import seaborn
import [Link] as plt
Output :
Comment D deepa… Follow 14
As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know
Matplotlib, you are already half way through Seaborn.
[Link]() :
[Link] uses many arguments as input, main of which are described below in form of table:
Arguments Description
Value
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')
Output :
Example 2:
# importing packages
import seaborn
import [Link] as plt
# loading dataset
df = seaborn.load_dataset('tips')
Output:
Comment D deepa… Follow 7
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.
Output :
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 :
Parameters :
Parameter Value Use
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.
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
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
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.
# selecting style
[Link](style ="ticks")
Output :
# selecting style
[Link](style ="ticks")
Output :
Example 3: using time and sex for determining the facet of the grid.
# selecting style
[Link](style ="ticks")
Output :
Example 4: using size attribute, we can see data points having different size.
# selecting style
[Link](style ="ticks")
Output :
Comment 09amit Follow 7
tips = sns.load_dataset('tips')
[Link](x ="total_bill", y ="tip", data = tips)
Output :
[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".
[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 :
Parameters :
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
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
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:
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 :
sizes list, dict, or tuple; optional determines the size of each point in the plot.
int, [Link], or
Seed or random number generator for reproducible
seed [Link];
bootstrapping.
optional
[Link](style = 'whitegrid')
fmri = sns.load_dataset("fmri")
Output :
Example 2: Grouping data points on the basis of category, here as region and event.
[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.
[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 :
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
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.
[Link](style='whitegrid')
fmri = sns.load_dataset("fmri")
Output
Using [Link]()
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]()
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]()
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.
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.
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.
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.
Output
5. Adding size attributes: Using size we can generate the point and we can produce points with
different sizes.
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.
Output
7. Adding alpha attributes: Using alpha we can control proportional opacity of the points. We can
decrease and increase the opacity.
Output
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
# 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:
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:
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
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 :
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
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
Example 1:
# 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")
Output :
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.
tips = sns.load_dataset("tips")
Output :
scatterplot3
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.
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.
# 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
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'],
# 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'],
[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'],
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'],
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)
ax[1][1].tick_params(labelrotation = 25)
fig.tight_layout(pad = 1.2)
Output :
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.
Output:
[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.
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
[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.
Article Tags: Technical Scripter Python Technical Scripter 2020 Python-pandas +3 More
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.
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.
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:
Output :
Output :
Example 4: Plot all bars in a given order.
Control barplot order by passing an explicit order.
Output :
Example 5: Plot all bars in a single color using color attributes.
Color for all of the elements.
Syntax:
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:
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:
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,
Example 8: Using the statistical function [Link] and [Link] to estimate within
each categorical bin.
Output:
For [Link]:
Output:
Output:
Output:
Comment A ankthon Follow 7
[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:
[Link]()
Output :
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.
[Link]()
Output:
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.
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.
[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.
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.
[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.
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
[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.
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.
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.
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.
# 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.
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.
df = sns.load_dataset("tips")
[Link](x="day", y="tip", data=df)
[Link]()
Output:
Syntax:
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.
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.
df = sns.load_dataset("tips")
[Link](x=df["total_bill"])
[Link]()
Output:
Horizontal boxplot
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.
df = sns.load_dataset("tips")
[Link](x="day", y="total_bill", hue="smoker", data=df)
[Link]()
Output:
Boxplot with Hue
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.
df = sns.load_dataset("tips")
palette = {'Male': 'skyblue', 'Female': 'lightpink'}
[Link](x="day", y="tip", hue="sex", data=df, palette=palette)
[Link]()
Output:
The linewidth parameter controls thickness of the boxplot lines. By increasing it plot’s boundaries
become more thick.
df = sns.load_dataset("tips")
[Link](x="day", y="tip", data=df, linewidth=2)
[Link]()
Output:
In this example we plot multiple variables horizontally by setting the orient parameter to "h". This
helps in comparing distributions of multiple numerical columns.
df = sns.load_dataset("tips")
[Link](data=df[["total_bill", "tip", "size"]], orient="h")
[Link]()
Output:
Horizontal Boxplot for Multiple Columns
We can use color parameter to set a single color for the entire boxplot which ensures a uniform
color.
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