Numpy 4
Numpy 4
Tutorials
Practice V
Jobs
Python for Machine Learning Machine Learning with R Machine Learning Algorithms EDA Math for Machine Learning Machine Learning Inte
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface
for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major
problems faced by Matplotlib; the problems are?
Default Matplotlib parameters
Working with data frames
As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know
Matplotlib, you are already half-way through Seaborn. Seaborn library offers many advantages over
other plotting libraries:
It is very easy to use and requires less code syntax
Works really well with `pandas` data structures, which is just what you need as a data scientist.
It is built on top of Matplotlib, another vast and deep data visualization library.
Parameters
exercise = sns.load_dataset("exercise")
g = [Link](x="time", y="pulse",
hue="kind",
data=exercise)
Output:
For the count plot, we set a kind parameter to count and feed in the data using data parameters. Let's
start by exploring the time feature. We start off with catplot() function and use x argument to specify
the axis we want to show the categories.
sns.set_theme(style="ticks")
exercise = sns.load_dataset("exercise")
g = [Link](x="time",
kind="count",
data=exercise)
Output:
Another popular choice for plotting categorical data is a bar plot. In the count plot example, our plot
only needed a single variable. In the bar plot, we often use one categorical variable and one
quantitative. Let’s see how the time compares to each other.
Output:
For creating the horizontal bar plot we have to change the x and y features. When you have lots of
categories or long category names it's a good idea to change the orientation.
exercise = sns.load_dataset("exercise")
g = [Link](x="pulse",
y="time",
kind="bar",
data=exercise)
Output:
exercise = sns.load_dataset("exercise")
g = [Link](x="time",
y="pulse",
hue="kind",
data=exercise,
kind="violin")
Output:
import seaborn as sns
exercise = sns.load_dataset("exercise")
g = [Link](x="time",
y="pulse",
hue="kind",
col="diet",
data=exercise)
Output:
Make many column facets and wrap them into the rows of the grid. The aspect will change the width
while keeping the height constant.
titanic = sns.load_dataset("titanic")
g = [Link](x="alive", col="deck", col_wrap=4,
data=titanic[[Link]()],
kind="count", height=2.5, aspect=.8)
Output:
Plot horizontally and pass other keyword arguments to the plot function:
g = [Link](x="age", y="embark_town",
hue="sex", row="class",
data=titanic[titanic.embark_town.notnull()],
orient="h", height=2, aspect=3, palette="Set3",
kind="violin", dodge=True, cut=0, bw=.2)
Output:
Box plots are visuals that can be a little difficult to understand but depict the distribution of data very
beautifully. It is best to start the explanation with an example of a box plot. I am going to use one of
the common built-in datasets in Seaborn:
tips = sns.load_dataset('tips')
[Link](x='day',
y='total_bill',
data=tips,
kind='box');
Output:
The edges of the blue box are the 25th and 75th percentiles of the distribution of all bills. This
means that 75% of all the bills on Thursday were lower than 20 dollars, while another 75% (from
the bottom to the top) was higher than almost 13 dollars. The horizontal line in the box shows the
median value of the distribution.
Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%
The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQR
The upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR
Comment V vivekpi… Follow 2
Prerequisite: Seaborn
Ridgeline plot is a set of overlapped density plots that help in comparing multiple distributions
among datasets. The Ridgeline plots look like a mountain range, they can be quite useful for
visualizing changes in distributions over time or space. Sometimes it is also known as "joyplot", in
reference to the iconic cover art for Joy Division’s album Unknown Pleasures. In this article, We will
see how to generate Ridgeline plots for the dataset.
Installation
Like any another python library, seaborn can be easily installed using pip:
This library is a part of Anaconda distribution and usually works just by import if your IDE is
supported by Anaconda, but it can be installed too by the following command:
Procedure
Load the packages required to generate the Ridgeline plot with Python.
Read the Dataset. In this example, we use the read_csv() method to load the dataset. In the given
example we will only display the top 5 entries using the head() method.
Generate RidgePlot. The Ridgeline Plot uses faceting meaning it creates small multiples, in a
single column. To generate Ridgeline Plot Seaborn uses FacetGrid() method and all required
information should be passed to it
Parameters:
1. data: Tidy (“long-form”) dataframe where each column is a variable and each row is an
observation.
2. row, col, hue: Variables that define subsets of the data, which will be drawn on separate
facets in the grid.
3. height: Height (in inches) of each facet.
4. aspect: Aspect ratio of each facet, so that aspect * height gives the width of each facet in
inches.
5. palette: Colors to use for the different levels of the hue variable.
Use the map() method to creates a density plot in each element of the grid. In this example, we
need a density plot so use kdeplot() method which available in Seaborn.
Sample Database: Dataset used in the following example is downloaded from [Link]. The
following link can be used for the same.
Example:
df = pd.read_csv("titanic_train.csv")
[Link]()
le = [Link]()
df["Sex"] = le.fit_transform(df["Sex"])
Output :
Change Axis Labels, Set Title and Figure Size to Plots with Seaborn
Last Updated : 23 Jul, 2025
Seaborn is Python's visualization library built as an extension to Matplotlib. Seaborn has Axes-level
functions (scatterplot, regplot, boxplot, kdeplot, etc.) as well as Figure-level functions (lmplot,
factorplot, jointplot, relplot etc.). Axes-level functions return Matplotlib axes objects with the plot
drawn on them while figure-level functions include axes that are always organized in a meaningful
way. The basic customization that a graph needs to make it understandable is setting the title,
setting the axis labels, and adjusting the figure size. Any customization made is on the axes object for
axes-level functions and the figure object for figure-level functions.
Note: Axes in the above explanation refers to a part of the figure or the top layer of a figure and is
not the mathematical term for more than one axis. Consider a plot on a figure. This plot axes. Now,
consider multiple subplots on a figure. Each of these subplots is one axes.
Let us see some examples to better understand customization with Seaborn.
Output:
Output:
# Plot scatterplot
[Link]( x = "total_bill" , y = "tip" , data = tips )
# Display figure
[Link]()
Output:
Output:
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface
for drawing attractive and informative statistical graphics. Basically, it helps us stylize our basic plot
made using matplotlib. Moreover, it also provides us different plotting techniques to ease our
Exploratory Data Analysis(EDA). With these plots, it also becomes important to provide legends for
a particular plot.
In this following article, we are going to see how can we place our Legend on our plot, and later in
this article, we will also see how can we place the legend outside the plot using Seaborn.
We will start by importing our necessary libraries.
We will be using Seaborn for not only plotting the data but also importing our dataset. Here we will
be using the Gamma dataset by seaborn.
[Link]()
Output:
We can see that this plots a beautiful line plot graph with the legends. We can see that the legend
box is on the plot. This might be an issue in many plots, so we need to keep our legend box outside
the plot.
We can do this by using matplotlib's legend function and providing its necessary parameters.
Output:
Output:
Hence, this technique can be used in many scenarios where the legend box comes on the graph
which may be otherwise useful for our EDA.
Confidence Interval is a type of estimate computed from the statistics of the observed data which
gives a range of values that's likely to contain a population parameter with a particular level of
confidence.
A confidence interval for the mean is a range of values between which the population mean possibly
lies. If I'd make a weather prediction for tomorrow of somewhere between -100 degrees and +100
degrees, I can be 100% sure that this will be correct. However, if I make the prediction to be between
20.4 and 20.5 degrees Celsius, I'm less confident. Note how the confidence decreases, as the interval
decreases. The same applies to statistical confidence intervals, but they also rely on other factors.
A 95% confidence interval, will tell me that if we take an infinite number of samples from my
population, calculate the interval each time, then in 95% of those intervals, the interval will contain
the true population mean. So, with one sample we can calculate the sample mean, and from there
get an interval around it, that most likely will contain the true population mean.
Area under the two black lines shows the 95% confidence interval
Confidence Interval as a concept was put forth by Jerzy Neyman in a paper published in 1937. There
are various types of the confidence interval, some of the most commonly used ones are: CI for mean,
CI for the median, CI for the difference between means, CI for a proportion and CI for the difference in
proportions.
Let's have a look at how this goes with Python.
Computing C.I given the underlying distribution using lineplot()
The lineplot() function which is available in Seaborn, a data visualization library for Python is best to
show trends over a period of time however it also helps in plotting the confidence interval.
Syntax:
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.
By default, the plot aggregates over multiple y values at each value of x and shows an estimate of
the central tendency and a confidence interval for that estimate.
Example:
# import libraries
import numpy as np
import seaborn as sns
import [Link] as plt
# create lineplot
ax = [Link](x, y)
In the above code, variable x will store 100 random integers from 0 (inclusive) to 30 (exclusive) and
variable y will store 100 samples from the Gaussian (Normal) distribution which is centred at 0 with
spread/standard deviation 1. NumPy operations are usually done on pairs of arrays on an element-
by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the
above example. Finally, a lineplot is created with the help of seaborn library with 95% confidence
interval by default. The confidence interval can easily be changed by changing the value of the
parameter 'ci' which lies within the range of [0, 100], here I have not passed this parameter hence it
considers the default value 95.
The light blue shade indicates the confidence level around that point if it has higher confidence the
shaded line will be thicker.
x, y: These are Input variables. If strings, these should correspond with column names in
"data". When pandas objects are used, axes will be labeled with the series name.
data: This is dataframe where each column is a variable and each row is an observation.
lowess: (optional) This parameter take boolean value. If "True", use "statsmodels" to
estimate a nonparametric lowess model (locally weighted linear regression).
color: (optional) Color to apply to all plot elements.
marker: (optional) Marker to use for the scatterplot glyphs.
Basically, it includes a regression line in the scatterplot and helps in seeing any linear relationship
between two variables. Below example will show how it can be used to plot confidence interval as
well.
Example:
# import libraries
import numpy as np
import seaborn as sns
import [Link] as plt
The regplot() function works in the same manner as the lineplot() with a 95% confidence interval by
default. Confidence interval can easily be changed by changing the value of the parameter 'ci' which
lies in the range of [0, 100]. Here I have passed ci=80 which means instead of the default 95%
confidence interval, an 80% confidence interval is plotted.
The width of light blue color shade indicates the confidence level around the regression line.
Computing C.I. using Bootstrapping
Bootstrapping is a test/metric that uses random sampling with replacement. It gives the measure of
accuracy (bias, variance, confidence intervals, prediction error, etc.) to sample estimates. It allows the
estimation of the sampling distribution for most of the statistics using random sampling methods. It
may also be used for constructing hypothesis tests.
Example:
# import libraries
import pandas
import numpy
from [Link] import resample
from [Link] import accuracy_score
from matplotlib import pyplot as plt
# load dataset
x = [Link]([180,162,158,172,168,150,171,183,165,176])
# configure bootstrap
n_iterations = 1000 # here k=no. of bootstrapped samples
n_size = int(len(x))
# run bootstrap
medians = list()
for i in range(n_iterations):
s = resample(x, n_samples=n_size);
m = [Link](s);
[Link](m)
# plot scores
[Link](medians)
[Link]()
# confidence intervals
alpha = 0.95
p = ((1.0-alpha)/2.0) * 100
lower = [Link](medians, p)
p = (alpha+((1.0-alpha)/2.0)) * 100
upper = [Link](medians, p)
Article Tags: Technical Scripter Python Technical Scripter 2020 Python-matplotlib +2 More
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
In this article, we will learn how to add a regression line per group with Seaborn in Python. Seaborn
has multiple functions to form scatter plots between two quantitative variables. For example, we can
use lmplot() function to make the required plot.
What is Regression Line?
A regression line is just one line that most closely fits the info (in terms of getting the littlest overall
distance from the road to the points). Statisticians call this system for locating the best-fitting line an
easy rectilinear regression analysis using the smallest amount squares method.
Steps Required
1. Import Library.
2. Import or create data.
3. Use lmplot method. This method is used to add a regression line per group by simply adding the
hue parameter with the categorical variable name.
4. Use different arguments for better visualization.
Example 1:
# import libraries
import seaborn
# load data
tip = seaborn.load_dataset('tips')
# use lmplot
[Link](x="total_bill",
y="size",
hue="sex",
data=tip)
Output:
Example 2:
# import libraries
import seaborn
# load data
tip = seaborn.load_dataset('tips')
# use lmplot
[Link](x="total_bill",
y="tip",
hue="day",
markers='*',
data=tip)
Output:
Example 3:
# import libraries
import seaborn
# load data
iris = seaborn.load_dataset('iris')
# use lmplot
[Link](x="sepal_length",
y="sepal_width",
hue="species",
markers='+',
data=iris)
Output:
Comment D deepa… Follow
Seaborn is a popular Python library for creating attractive statistical visualizations. Built on Matplotlib and
integrated with Pandas, it simplifies complex plots like line charts, heatmaps and violin plots with minimal
code.
2/4
Let’s see various types of plots with simple code to understand how to use it effectively.
1. Line plot
A line plot shows the relationship between two numeric variables, often over time. It can also compare
multiple groups using different lines.
Syntax:
Parameters:
x, y: Numeric input variables. These can be arrays, lists or column names from a DataFrame.
data: DataFrame containing the data.
Example:
import pandas as pd
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)
[Link]([Link], df['Age'])
[Link]('Index')
[Link]('Age')
[Link]('Age Line Plot')
[Link]()
Output
Line plot
2. Scatter Plot
Scatter plots are used to visualize the relationship between two numerical variables. They help identify
correlations or patterns. It can draw a two-dimensional graph.
Syntax:
Parameters:
x, y: Input data variables that should be numeric.
data (optional): Dataset containing the variables.
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)
Output
Scatter plot
3. Box plot
A box plot is the visual representation of the depicting groups of numerical data with their quartiles against
continuous/categorical data.
It consists of 5 key statistics: Minimum ,First Quartile or 25% , Median (Second Quartile) or 50%, Third
Quartile or 75% and Maximum
Syntax:
Parameters:
import pandas as pd
import [Link] as plt
import seaborn as sns
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 45]}
df = [Link](data)
[Link](y='Age', data=df)
[Link]()
Output
Box plot
4. Violin Plot
A violin plot is similar to a boxplot. It shows several quantitative data across one or more categorical
variables such that those distributions can be compared.
Syntax:
Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting.
Example:
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)
[Link](y='Age', data=df)
[Link]()
Output
Violin plot
5. Swarm plot
A swarm plot displays individual data points without overlap along a categorical axis which provides a clear
view of distribution density.
Syntax:
Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting.
Example:
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)
Output
Swarmplot
6. Bar plot
Barplot represents an estimate of central tendency for a numeric variable with the height of each rectangle
and provides some indication of the uncertainty around that estimate using error bars.
Syntax:
Parameters :
x, y : Variables or column names for long-form data.
hue : (optional) Column for color encoding.
data : (optional) Dataset to plot.
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'], 'Age': [21, 23, 20, 24]}
df = [Link](data)
Output
Bar plot
7. Point plot
Point plot show point estimates and confidence intervals using scatter glyphs which represents the central
tendency of a numeric variable.
Syntax:
Parameters:
x, y: Inputs for plotting long-form data.
hue: (optional) column name for color encoding.
data: Dataframe as a Dataset for plotting.
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'JAYAN', 'ANURAG'],'Age': [21, 23, 20, 24]}
df = [Link](data)
Output
Point Plot
8. Count plot
A Count plot displays the number of occurrences of each category using bars to visualize the distribution of
categorical variables.
Syntax :
Parameters :
x, y: Inputs for plotting long-form data.
hue: (optional) column name for color encoding.
data: Dataframe as a Dataset for plotting.
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {'Name': ['ANSH', 'SAHIL', 'ANSH', 'JAYAN', 'ANURAG', 'ANURAG', 'ANURAG', 'SAHIL']}
df = [Link](data)
[Link](x='Name', data=df)
[Link]("Frequency of Names")
[Link]()
Output
Countplot
9. KDE Plot
KDE Plot (Kernel Density Estimate) is used for visualizing the Probability Density of a continuous variable
at different values in a continuous variable. We can also plot a single graph for multiple samples which
helps in more efficient data visualization.
Syntax:
Parameters:
x, y: Vectors or data keys.
vertical: Boolean to plot vertically.
palette: Color palette.
data: Dataframe
Example:
iris = load_iris()
df = [Link]([Link], columns=iris.feature_names)
df['Species'] = [Link]
df['Species'] = df['Species'].map({ 0: 'Setosa', 1: 'Versicolor', 2: 'Virginica'})
Output
KDE plot
Adding descriptive titles and axis labels makes our plots more understandable and informative. Using
Matplotlib's [Link](), [Link]() and [Link]() to set titles and axis labels.
iris = sns.load_dataset('iris')
[Link](x='sepal_length', y='sepal_width', data=iris)
Output
Adding Titles and Labels
Seaborn provides built-in styles that control the background and grid of your plots. These styles improve
readability and can be chosen based on your presentation needs.
Available Styles:
darkgrid – Dark background with light gridlines. Great for clear contrast.
whitegrid – White background with light gridlines. Ideal for statistical plots.
dark – Dark background without gridlines. Clean and modern look.
white – Plain white background without gridlines. Good for simple visuals.
ticks – White background with axis ticks styled sharply. Suitable for publications.
sns.set_style("whitegrid")
Output
Representation of Whitegrid in Boxplot
Seaborn makes it easy to enhance the appearance of plots using color palettes. You can choose from built-in
palettes like "deep", "muted", or "bright" or define your own using sns.color_palette(). Customizing colors
improves clarity and helps match your data’s theme or purpose.
a) Using a Built-in Palette:
sns.set_palette("pastel")
Output
Using Built in palette
[Link](figsize=(10, 6))
Output
Markers can be added to Seaborn line plots using the marker argument to highlight data points. For
example adding circular markers to the line plot using [Link](x='x', y='y' ,marker='o')
Output
Adding marker to lne plot
1. Pair Plots
Pair plots are used explore relationships between several variables by generating scatter plots for every
pair of variables in a dataset along with univariate distributions on the diagonal. This is useful for exploring
datasets with multiple variables and seeing potential correlations.
Syntax:
[Link](data, hue=None)
Parameters:
data: Dataset to plot.
hue: (optional) Categorical variable used for color coding data points.
Returns: An array of Axes objects containing the scatter plot grid and distributions.
Example:
sns.set_style("whitegrid")
custom_palette = sns.color_palette("husl", 8)
sns.set_palette(custom_palette)
data = sns.load_dataset("iris")
[Link](data, hue="species")
[Link]()
Output
Pair Plots
2. Joint Plots
Joint plots combine a scatter plot with the distributions of the individual variables. This allows for a quick
visual representation of how the variables are distributed individually and how they relate to one another.
Syntax:
Parameters:
x, y: Variables to plot.
data: Dataset to plot.
kind: Type of plot to display ('scatter', 'kde', 'reg' etc).
Returns:
An Axes object with the joint plot including scatter plot and distribution plots on the margins.
Example:
data = sns.load_dataset("tips")
[Link](x="total_bill", y="tip", data=data, kind="scatter", color="#008B8B")
[Link]()
Output
Joint plots
This creates a scatter plot between total_bill and tip with histograms of the individual distributions along
the margins. The kind parameter can be set to 'kde' for kernel density estimates or 'reg' for regression plots.
3. Grid Plot
Grid plots in Seaborn are used to create multiple subplots in a grid layout. Using Seaborn's FacetGrid we
can visualize how variables interact across different categories which makesit easier to compare groups or
conditions within our dataset.
Syntax:
Parameters:
data: Dataset to plot.
col, row: Variables for the columns and rows of the grid (categorical variables).
[Link]: The plotting function to apply to each facet.
Example: To use FacetGrid, we first need to initialize it with a dataset and specify the variables that will
form the row, column or hue dimensions of the grid. Here is an example using the tips dataset:
tips = sns.load_dataset("tips")
Output
regplot(): This function plots a scatter plot along with a linear regression Trending
Subjects
model fit.
Software and Technologies
lmplot(): This function also plots linear models but providesTools
more flexibility in handling multiple facets
and datasets.
tips = sns.load_dataset('tips')
Output:
Regression Plots
As we explore Seaborn functions and techniques we can create clear, customized and insightful
visualizations that helps us to understand our data better.
Which of the following Seaborn plots is used to visualize the relationship between two numerical variables?
A Bar plot
B Scatter plot
C Box plot
D Heatmap
Article Tags: Technical Scripter Data Visualization AI-ML-DS Technical Scripter 2020 +4 More
Search...
Tutorials
Practice V
Jobs
a Visualization Tutorial With Python Types Matplotlib Altair Plotly Computer Vision OpenCV Computer Graphics Tutorial Deep Learn
It may sometimes seem easier to go through a set of data points and build insights from it but usually
this process may not yield good results. There could be a lot of things left undiscovered as a result of
this process. Additionally, most of the data sets used in real life are too big to do any analysis
manually. This is essentially where data visualization steps in.
Data visualization is an easier way of presenting the data, however complex it is, to analyze trends
and relationships amongst variables with the help of pictorial representation.
The following are the advantages of Data Visualization
Easier representation of compels data
Highlights good and bad performing areas
Explores relationship between data points
Identifies data patterns even for larger data points
While building visualization, it is always a good practice to keep some below mentioned points in
mind
Ensure appropriate usage of shapes, colors, and size while building visualization
Plots/graphs using a co-ordinate system are more pronounced
Knowledge of suitable plot with respect to the data types brings more clarity to the information
Usage of labels, titles, legends and pointers passes seamless information the wider audience
Python Libraries
There are a lot of python libraries which could be used to build visualization like matplotlib, vispy,
bokeh, seaborn, pygal, folium, plotly, cufflinks, and networkx. Of the many, matplotlib and seaborn
seems to be very widely used for basic to intermediate level of visualizations.
Matplotlib
Seaborn
Conceptualized and built originally at the Stanford University, this library sits on top of matplotlib. In
a sense, it has some flavors of matplotlib while from the visualization point, it is much better than
matplotlib and has added features as well. Below are its advantages
Built-in themes aid better visualization
Statistical functions aiding better data insights
Better aesthetics and built-in plots
Helpful documentation with effective examples
Nature of Visualization
Depending on the number of variables used for plotting the visualization and the type of variables,
there could be different types of charts which we could use to understand the relationship. Based on
the count of variables, we could have
Univariate plot(involves only one variable)
Bivariate plot(more than one variable in required)
A Univariate plot could be for a continuous variable to understand the spread and distribution of the
variable while for a discrete variable it could tell us the count
Similarly, a Bivariate plot for continuous variable could display essential statistic like correlation, for a
continuous versus discrete variable could lead us to very important conclusions like understanding
data distribution across different levels of a categorical variable. A bivariate plot between two
discrete variables could also be developed.
Box plot
A boxplot, also known as a box and whisker plot, the box and the whisker are clearly displayed in the
below image. It is a very good visual representation when it comes to measuring the data
distribution. Clearly plots the median values, outliers and the quartiles. Understanding data
distribution is another important factor which leads to better model building. If data has outliers, box
plot is a recommended way to identify them and take necessary actions.
Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form.
color: Color for all of the elements.
Returns: It returns the Axes object with the plot drawn onto it.
The box and whiskers chart shows how data is spread out. Five pieces of information are generally
included in the chart
1. The minimum is shown at the far left of the chart, at the end of the left ‘whisker’
2. First quartile, Q1, is the far left of the box (left whisker)
3. The median is shown as a line in the center of the box
4. Third quartile, Q3, shown at the far right of the box (right whisker)
5. The maximum is at the far right of the box
As could be seen in the below representations and charts, a box plot could be plotted for one or
more than one variable providing very good insights to our data.
Representation of box plot.
Scatter Plot
Scatter plots or scatter graphs is a bivariate plot having greater resemblance to line graphs in the
way they are built. A line graph uses a line on an X-Y axis to plot a continuous function, while a
scatter plot relies on dots to represent individual pieces of data. These plots are very useful to see if
two variables are correlated. Scatter plot could be 2 dimensional or 3 dimensional.
data: Dataframe where each column is a variable and each row is an observation.
size: Grouping variable that will produce points with different sizes.
style: Grouping variable that will produce points with different markers.
palette: Grouping variable that will produce points with different markers.
markers: Object determining how to draw the markers for different levels.
Returns: This method returns the Axes object with the plot drawn onto it.
# import module
import [Link] as plt
# scatter plot illustration
[Link](diabetes['DiabetesPedigreeFunction'], diabetes['BMI'])
# assign labels
ax.set_xlabel('X Label'), ax.set_ylabel('Y Label'), ax.set_zlabel('Z Label')
# display illustration
[Link]()
Histogram
Histograms display counts of data and are hence similar to a bar chart. A histogram plot can also tell
us how close a data distribution is to a normal curve. While working out statistical method, it is very
important that we have a data which is normally or close to a normal distribution. However,
histograms are univariate in nature and bar charts bivariate.
A bar graph charts actual counts against categories e.g. height of the bar indicates the number of
items in that category whereas a histogram displays the same categorical variables in bins.
Bins are integral part while building a histogram they control the data points which are within a
range. As a widely accepted choice we usually limit bin to a size of 5-20, however this is totally
governed by the data points which is present.
# illustrate histogram
features = ['BloodPressure', 'SkinThickness']
diabetes[features].hist(figsize=(10, 4))
Output Histogram
Countplot
A countplot is a plot between a categorical and a continuous variable. The continuous variable in this
case being the number of times the categorical is present or simply the frequency. In a sense, count
plot can be said to be closely linked to a histogram or a bar graph.
x, y: This parameter take names of variables in data or vector data, optional, Inputs for
plotting long-form data.
hue : (optional) This parameter take column name for colour encoding.
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting.
If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-
form.
order, hue_order : (optional) This parameter take lists of strings. Order to plot the
categorical levels in, otherwise the levels are inferred from the data objects.
orient : (optional)This parameter take “v” | “h”, Orientation of the plot (vertical or horizontal).
This is usually inferred from the dtype of the input variables but can be used to specify when
the “categorical” variable is a numeric or when plotting wide-form data.
color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed
for a gradient palette.
palette : (optional) This parameter take palette name, list, or dict, Colors to use for the
different levels of the hue variable. Should be something that can be interpreted by
color_palette(), or a dictionary mapping hue levels to matplotlib colors.
saturation : (optional) This parameter take float value, Proportion of the original saturation
to draw colors at. Large patches often look better with slightly desaturated colors, but set
this to 1 if you want the plot colors to perfectly match the input color spec.
dodge : (optional) This parameter take bool value, When hue nesting is used, whether
elements should be shifted along the categorical axis.
ax : (optional) This parameter take matplotlib Axes, Axes object to draw the plot onto,
otherwise uses the current Axes.
kwargs : This parameter take key, value mappings, Other keyword arguments are passed
through to [Link]().
Returns: Returns the Axes object with the plot drawn onto it.
It simply shows the number of occurrences of an item based on a certain type of [Link] python,
we can create a count plot using the seaborn library. Seaborn is a module in Python that is built on
top of matplotlib and used for visually appealing statistical plots.
Output Countplot
Correlation plot
Correlation plot is a multi-variate analysis which comes very handy to have a look at relationship
with data points. Scatter plots helps to understand the affect of one variable over the other.
Correlation could be defined as the affect which one variable has over the other.
Correlation could be calculated between two variables or it could be one versus many correlations as
well which we could see the below plot. Correlation could be positive, negative or neutral and the
mathematical range of correlations is from -1 to 1. Understanding the correlation could have a very
significant effect on the model building stage and also understanding the model outputs.
# adjust plot
[Link](rc={'[Link]': (14, 5)})
# assign data
ind_var = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM',
'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']
Heat Maps
Heat map is a multi-variate data representation. The color intensity in a heat map displays becomes
an important factor to understand the affect of data points. Heat maps are easier to understand and
easier to explain as well. When it comes to data analysis using visualization, its very important that
the desired message gets conveyed with the help of plots.
Syntax:
Parameters : This method is accepting the following parameters that are described below:
x, y: This parameter take names of variables in data or vector data, optional, Inputs for
plotting long-form data.
hue : (optional) This parameter take column name for colour encoding.
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting.
If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-
form.
color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed
for a gradient palette.
palette : (optional) This parameter take palette name, list, or dict, Colors to use for the
different levels of the hue variable. Should be something that can be interpreted by
color_palette(), or a dictionary mapping hue levels to matplotlib colors.
ax : (optional) This parameter take matplotlib Axes, Axes object to draw the plot onto,
otherwise uses the current Axes.
kwargs : This parameter take key, value mappings, Other keyword arguments are passed
through to [Link]().
Returns: Returns the Axes object with the plot drawn onto it.
# import required module
import seaborn as sns
import numpy as np
# assign data
data = [Link](50, 20)
Pie Chart
Pie chart is a univariate analysis and are typically used to show percentage or proportional data. The
percentage distribution of each class in a variable is provided next to the corresponding slice of the
pie. The python libraries which could be used to build a pie chart is matplotlib and seaborn.
Parameters:
data represents the array of data values to be plotted, the fractional area of each slice is
represented by data/sum(data). If sum(data)<1, then the data values returns the fractional area
directly, thus resulting pie will have empty wedge of size 1-sum(data).
labels is a list of sequence of strings which sets the label of each wedge.
color attribute is used to provide color to the wedges.
autopct is a string used to label the wedge with their numerical value.
shadow is used to create shadow of wedge.
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
fig = [Link](figsize=(10, 7))
[Link](data, labels=cars)
# Show plot
[Link]()
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}
# Creating plot
fig, ax = [Link](figsize=(10, 7))
wedges, texts, autotexts = [Link](data, autopct=lambda pct: func(pct, data), explode=explode, labels=cars,
shadow=True, colors=colors, startangle=90, wedgeprops=wp,
textprops=dict(color="magenta"))
# Adding legend
[Link](wedges, cars, title="Cars", loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
[Link](autotexts, size=8, weight="bold")
ax.set_title("Customizing pie chart")
# Show plot
[Link]()
Output
Error Bars
Error bars could be defined as a line through a point on a graph, parallel to one of the axes, which
represents the uncertainty or error of the corresponding coordinate of the point. These types of plots
are very handy to understand and analyze the deviations from the target. Once errors are identified, it
could easily lead to deeper analysis of the factors causing them.
Deviation of data points from the threshold could be easily captured
Easily captures deviations from a larger set of data points
It defines the underlying data
# Assign axes
x = [Link](0,5.5,10)
y = 10*[Link](-x)
# Adjust plot
fig, ax = [Link]()
[Link](x, y, xerr=xerr, yerr=yerr, fmt='-o')
# Assign labels
ax.set_xlabel('x-axis'), ax.set_ylabel('y-axis')
ax.set_title('Line plot with error bars')
# Illustrate error bars
[Link]()
Working on data can sometimes be a bit boring. Transforming a raw data into an understandable
format is one of the most essential part of the whole process, then why to just stick around on
numbers, when we can visualize our data into mind-blowing graphs which are up for grabs in python.
This article will focus on exploring plots which could make your preprocessing journey, intriguing.
Seaborn and Matplotlib provide us with numerous alluring graphs through which one can easily
analyze weak points, explore data with a deeper understanding and eventually end up getting a
great insight into data and gaining the highest accuracy after training it through different algorithms.
Let's Have A Glance Through Our Dataset : The Dataset (36 rows) contains 6 Features And 2
Classes (Survived = 1, Not Survived = 0 ) Based on which we'll plot certain graphs. Link of the
dataset - Click Here To Get Complete Dataset
1. KDE PLOT : Okay So after having a glance through the dataset we can have a question. Which
Age Group Has Maximum No. Of People? To answer this question we need visuals where Our KDE
Plot comes into the picture, it is simply a density plot. So let's start with importing required libraries
and use its functions to plot the graph.
# KDE plot
[Link](dataset["Age"], color = "green", Loading Playground...
shade = True)
[Link]()
[Link]()
Output :
2. So now we have a clear picture of how the Count Of People vs Age-Group is distributed, here we
can see that the age group 20-40 has maximum count so let's check it.
Output :
26
3. Digging deeper into visuals, to know about the variation in Fair Vs Age, what is the relation
between them, let's have a look using a different kind of kdeplot simply now there'll be bivariate
densities, we will just add the Y Variable(Fair).
Output :
4. After Studying this plot a bit, we see that the intensity of the color is maximum between the age
group 20-30 and precisely these have a fair between 100-200, let's check it
Output :
16
5. We can also add a histogram to kdeplot just by using distplot() module of seaborn :
# Histogram+Density Plot
[Link](dataset["Age"], color = "green") Loading Playground...
[Link]()
[Link]()
Output :
6. Well. If one wants to know about the Male Vs Female Proportion, We can plot the same in KDE
itself :
Output :
7. As We can see from the plot there is an increase in the count after Age 12 till Age 40, let's check
for the same
Output :
17
15
8. VIOLIN PLOT : We have talked much about the features, now let's talk about Survival Rate
Dependency On Features. For This, We will use a classic Violin Plot, as the name suggests it portrays
the same visuals as that of the musical waves of a violin. Basically A Violin Plot is used to visualize
the distribution of the data and its probability density.
What is the Relation Between Survival Rate And Age? Let's Visually Analyze It :
Output :
Explanation : The white dot we see in the plot is median and thick black bar in the center represents
the interquartile
[Link] thin black line extended from it represents the upper (max) and lower (min) adjacent
values in the data.
A Quick glance show's us that between Age[10-20] The Survival Rate is A bit higher(Survived==1).
9. Let's plot one more for the Survival Rate Vs Gender and Age
Here an additional attribute is hue, which refers to the binary value for Survived.
Output :
10. CATPLOT : In simple terms, catplot shows frequencies (or optionally fractions or percents) of the
categories of one, two, or three categorical variables.
Here [Link] is used to remove the top and right spines from the plot, let's have a look at it.
Output :
Here We get a clear picture of Gender Wise Survival Probability w.r.t No. Of Siblings.
11. Now, in The Dataset We See There Are Three Categories in Ticket, Which is based on Fare, Let's
Find About It (Referring This Plot I Added A Category Column For Tickets)
Output :
Using This we concluded that categories should be defined for tickets
12. Relation of the same with Survival Rate :
Output :
From this, we get a clear insight for Survival Rate Vs Fare w.r.t Category of Tickets.
The Binomial Distribution models the number of successes in a fixed number of independent trials
where each trial has only two outcomes: success or failure. In NumPy, we use the
[Link]() method to generate values that follow this distribution. It is commonly
used in coin flips, defect detection, surveys, and probability experiments.
Example: Here, we generate one binomial random value using 10 trials and a 0.5 probability of
success.
import numpy as np
x = [Link](n=10, p=0.5)
print(x)
Output
Explanation: [Link](n=10, p=0.5) simulates 10 yes/no events and returns how many
times success occurred.
Syntax
[Link](n, p, size=None)
Parameters:
n: Number of trials
p: Probability of success in each trial
size: Shape of output array
Examples
Example 1: In this example, we generate 5 binomial random numbers using 10 trials and 0.5
probability.
import numpy as np
arr = [Link](n=10, p=0.5, size=5)
print(arr)
Output
[7 2 5 4 7]
import numpy as np
x = [Link](8, 0.3, size=4)
print(x)
Output
[4 4 4 4]
Explanation: [Link](8, 0.3) generates values where success occurs with 30%
probability.
import numpy as np
m = [Link](12, 0.6, size=(2, 3))
print(m)
Output
[[8 7 9]
[6 8 5]]
Explanation: size=(2,3) creates a 2D array where each entry is a binomial random value.
import numpy as np
import [Link] as plt
from [Link] import binom
n = 10
p = 0.5
size = 1000
x = [Link](0, n+1)
pmf = [Link](x, n, p)
Explanation:
[Link](n, p, size) generates 1000 simulated outcomes.
[Link](..., density=True) shows the frequency distribution of these values.
[Link](x, n, p) computes the theoretical probability for each possible success count.
Red dots and dashed lines show the true Binomial PMF for comparison.
The [Link]() function is used to change the size of an existing NumPy array. It modifies the
array permanently and adjusts its shape to the new dimensions. If the new shape requires more
elements than available, NumPy repeats the array elements. If less space is required, elements are
truncated.
Example 1: This example resizes a 1D array of 6 elements into a 2×3 array. No values need
repetition or truncation.
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
[Link]((2, 3))
print(arr)
Loading Playground...
Output
[[1 2 3]
[4 5 6]]
Syntax
[Link](a, new_shape)
Parameters:
a: Input array to be resized.
new_shape: Target shape (int or tuple).
refcheck(optional): If True, checks whether the array is referenced elsewhere before resizing.
Example 2: This example resizes a 6-element array into a 3×4 shape (12 elements needed). NumPy
repeats the array elements to fill the new size.
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
[Link]((3, 4))
print(arr)
Loading Playground...
Output
[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]
Example 3: This example resizes an array into a 2×2 shape. Since fewer elements are required, the
extra values are removed.
import numpy as np
arr = [Link]([10, 20, 30, 40, 50])
[Link]((2, 2))
print(arr)
Loading Playground...
Output
[[10 20]
[30 40]]