0% found this document useful (0 votes)
5 views53 pages

Notes

Uploaded by

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

Notes

Uploaded by

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

ACHARYA INSTITUTE OF TECHNOLOGY

Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.


Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

MODULE 3

Resampling, Shifting, and Windowing in Pandas


Why Time Series Indexing Matters
When your DataFrame or Series has a DatetimeIndex, pandas gives you powerful tools for time-
based operations.
These include:
Resampling → changing frequency of data
Shifting → moving data in time
Rolling Window → applying moving averages or statistics
Example Data:
from pandas_datareader import data
goog = [Link]('GOOG', start='2004', end='2016', data_source='google')

[Link]() → fetches data (here Google stock)


Parameters:
'GOOG' → stock symbol
start, end → date range
data_source='google' → where to pull data from

Then:
goog = goog['Close']

We keep only the Closing Price column.


Visualizing the Data
%matplotlib inline
import [Link] as plt
import seaborn as sns; [Link]()

[Link]();
This plots the time series of Google closing prices with date on the x-axis.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Resampling and Frequency Conversion:


Resampling means changing the frequency of time series data —
e.g., daily → monthly → yearly, or vice versa.
Pandas provides two methods
resample() → aggregation
asfreq() → reindexing or selection
Example:
[Link](alpha=0.5, style='-')
[Link]('BA').mean().plot(style=':')
[Link]('BA').plot(style='--')
[Link](['input', 'resample', 'asfreq'], loc='upper left')

'BA' Business Annual frequency i.e., end of business year


.resample('BA').mean() groups data by year and computes the average closing price for
each year
.asfreq('BA') simply selects the value at the end of each business year, no aggregation

Difference
resample() → summarizes data (aggregation)
asfreq() → just picks existing data points (selection)

Up-sampling (Lower → Higher Frequency)


Example:
fig, ax = [Link](2, sharex=True)
data = [Link][:10]

[Link]('D').plot(ax=ax[0], marker='o')
[Link]('D', method='bfill').plot(ax=ax[1], style='-o')
[Link]('D', method='ffill').plot(ax=ax[1], style='--o')
ax[1].legend(["back-fill", "forward-fill"]);
'D' Daily frequency (includes weekends)
method='bfill' backward fill — fill missing days with next valid value
method='ffill' forward fill — fill missing days with previous valid value
Result
Top chart → missing (NaN) values for non-business days

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Bottom chart → shows filled gaps using ffill & bfill strategies

Time Shifting:
Shift moves data forward or backward in time.
Two related methods
shift() shifts data values while keeping index fixed
tshift() shifts index (timestamps) while keeping data fixed
Example:
goog = [Link]('D', method='pad') # ensure daily frequency

fig, ax = [Link](3, sharey=True)


[Link](ax=ax[0])
[Link](900).plot(ax=ax[1])
[Link](900).plot(ax=ax[2])
[Link](900) moves values down by 900 days — NaNs appear at start
[Link](900) moves timestamps forward by 900 days

Visualization:
The plot shows original, shifted, and index-shifted series.
The difference is clear — shift() displaces values, tshift() moves time labels.

Example Use: Return on Investment (ROI)


We can use tshift() to compute how much a stock grows after a year:
ROI = 100 * ([Link](-365) / goog - 1)
[Link]()
[Link]('% Return on Investment');
Formula:

This shows percentage growth of Google stock over a rolling one-year window.

Rolling Windows (Moving Statistics)


A rolling window performs calculations over a fixed-size time window that “slides” along the
data.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Used for:
→ Moving average, moving standard deviation, volatility, etc.
Example:
rolling = [Link](365, center=True)
data = [Link]({
'input': goog,
'one-year rolling_mean': [Link](),
'one-year rolling_std': [Link]()
})
ax = [Link](style=['-', '--', ':'])
[Link][0].set_alpha(0.3)

.rolling(365) creates a rolling window of 365 days


center=True centers the window around each point
.mean() computes rolling average
.std() computes rolling standard deviation

Interpretation:

The dashed line → average over last year


The dotted line → fluctuation (volatility)
The solid line → actual price
Rolling statistics help smooth noisy time series and detect trends.

Down-sampling
[Link](rule, axis=0, closed=None, label=None, on=None,
level=None).agg_func()
rule → defines the new frequency (e.g., 'M' for monthly, 'W' for weekly, 'D' for
daily).
agg_func → function to apply within each resample group (mean(), sum(), max(),
etc.).
on → specify which column to use as date (if not already an index).
resample('M').mean() Reduce frequency (daily → monthly)Summarize or aggregate

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Up-sampling
[Link](freq, method=None, how=None, normalize=False)
freq → new frequency (e.g., 'D', 'M', 'W').
method → how to fill missing values ('ffill' = forward fill, 'bfill' = backward fill).
asfreq('D', method='ffill') Increase frequency (monthly → daily) Fill missing periods

Shift Data
[Link](periods=1, freq=None, axis=0, fill_value=None)
periods → number of steps to shift (positive = downward, negative = upward).
freq → optional, shifts index by time (e.g., 'D' for days).
fill_value → what to fill missing spaces with (default = NaN).
shift(n)Move values forward/backward Compute lag differences
Shift Index
[Link](periods=1, freq=None)
tshift(n) Move timestamps forward/backward Compare data across time
Rolling Window
[Link](window, min_periods=None, center=False,
win_type=None, on=None, axis=0, closed=None).agg_func()
window → number of observations per window (e.g., 3 = last 3 rows).
min_periods → minimum required observations to return a value.
agg_func → aggregation function (mean, sum, max, etc.).
.rolling(window).mean() Moving statistics Trend analysis, smoothing

Resampling Change frequency of data [Link]('M').mean()


Asfreq Select data at new frequency [Link]('M')
Shift Move data values [Link](30)
Tshift Move index [Link](30)
Rolling Moving calculations [Link](7).mean()

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

High-Performance Pandas: eval() and query()


As we've already seen in previous sections, the power of the PyData stack is built upon the
ability of NumPy and Pandas to push basic operations into C via an intuitive syntax: examples
are vectorized/broadcasted operations in NumPy, and grouping-type operations in Pandas. While
these abstractions are efficient and effective for many common use cases, they often rely on the
creation of temporary intermediate objects, which can cause undue overhead in computational
time and memory use.
As of version 0.13 (released January 2014), Pandas includes some experimental tools that
allow you to directly access C-speed operations without costly allocation of intermediate
arrays. These are the eval() and query() functions, which rely on the Numexpr package.

Motivating query() and eval(): Compound Expressions

We've seen previously that NumPy and Pandas support fast vectorized operations; for example,
when adding the elements of two arrays:
import numpy as np
rng = [Link](42)
x = [Link](1000000)
y = [Link](1000000)
%timeit x + y
100 loops, best of 3: 3.39 ms per loop
As discussed in Computation on NumPy Arrays: Universal Functions, this is much faster than
doing the addition via a Python loop or comprehension:

%timeit [Link]((xi + yi for xi, yi in zip(x, y)), dtype=[Link], count=len(x))


1 loop, best of 3: 266 ms per loop
But this abstraction can become less efficient when computing compound expressions. For
example, consider the following expression:
mask = (x > 0.5) & (y < 0.5)
Because NumPy evaluates each subexpression, this is roughly equivalent to the following:
tmp1 = (x > 0.5)
tmp2 = (y < 0.5)
mask = tmp1 & tmp2
In other words, every intermediate step is explicitly allocated in memory. If the x and y arrays
are very large, this can lead to significant memory and computational overhead.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The Numexpr library gives you the ability to compute this type of compound expression
element by element, without the need to allocate full intermediate arrays.
The Numexpr documentation has more details, but for the time being it is sufficient to say that
the library accepts a string giving the NumPy-style expression you'd like to compute:

import numexpr
mask_numexpr = [Link]('(x > 0.5) & (y < 0.5)')
[Link](mask, mask_numexpr)
True
The benefit here is that Numexpr evaluates the expression in a way that does not use full-
sized temporary arrays, and thus can be much more efficient than NumPy, especially for
large arrays.
The Pandas eval() and query() tools that we will discuss here are conceptually similar, and
depend on the Numexpr package.

[Link]() for Efficient Operations

The eval() function in Pandas uses string expressions to efficiently compute operations
using DataFrames. For example, consider the following DataFrames:

import pandas as pd
nrows, ncols = 100000, 100
rng = [Link](42)
df1, df2, df3, df4 = ([Link]([Link](nrows, ncols))
‘ i in range(4))
To compute the sum of all four DataFrames using the typical Pandas approach, we can just write
the sum:

%timeit df1 + df2 + df3 + df4


10 loops, best of 3: 87.1 ms per loop
The same result can be computed via [Link] by constructing the expression as a string:

%timeit [Link]('df1 + df2 + df3 + df4')


10 loops, best of 3: 42.2 ms per loop
The eval() version of this expression is about 50% faster (and uses much less memory), while
giving the same result:

[Link](df1 + df2 + df3 + df4,


[Link]('df1 + df2 + df3 + df4'))
True

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Operations supported by [Link]()

As of Pandas v0.16, [Link]() supports a wide range of operations. To demonstrate these, we'll
use the following integer DataFrames:

df1, df2, df3, df4, df5 = ([Link]([Link](0, 1000, (100, 3)))


for i in range(5))
Arithmetic operators
[Link]() supports all arithmetic operators. For example:

result1 = -df1 * df2 / (df3 + df4) - df5


result2 = [Link]('-df1 * df2 / (df3 + df4) - df5')
[Link](result1, result2)
True
Comparison operators
[Link]() supports all comparison operators, including chained expressions:

result1 = (df1 < df2) & (df2 <= df3) & (df3 != df4)
result2 = [Link]('df1 < df2 <= df3 != df4')
[Link](result1, result2)
True
Bitwise operators
[Link]() supports the & and | bitwise operators:

result1 = (df1 < 0.5) & (df2 < 0.5) | (df3 < df4)
result2 = [Link]('(df1 < 0.5) & (df2 < 0.5) | (df3 < df4)')
[Link](result1, result2)
True
In addition, it supports the use of the literal and and or in Boolean expressions:

result3 = [Link]('(df1 < 0.5) and (df2 < 0.5) or (df3 < df4)')
[Link](result1, result3)
True
Object attributes and indices
[Link]() supports access to object attributes via the [Link] syntax, and indexes via the
obj[index] syntax:

result1 = df2.T[0] + [Link][1]


result2 = [Link]('df2.T[0] + [Link][1]')
[Link](result1, result2)

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

True
Other operations
Other operations such as function calls, conditional statements, loops, and other more
involved constructs are currently not implemented in [Link](). If you'd like to execute these
more complicated types of expressions, you can use the Numexpr library itself.

[Link]() for Column-Wise Operations


Just as Pandas has a top-level [Link]() function, DataFrames have an eval() method that
works in similar ways. The benefit of the eval() method is that columns can be referred to by
name. We'll use this labeled array as an example:

df = [Link]([Link](1000, 3), columns=['A', 'B', 'C'])


[Link]()
A B C
0 0.375506 0.406939 0.069938
1 0.069087 0.235615 0.154374
2 0.677945 0.433839 0.652324
3 0.264038 0.808055 0.347197
4 0.589161 0.252418 0.557789
Using [Link]() as above, we can compute expressions with the three columns like this:

result1 = (df['A'] + df['B']) / (df['C'] - 1)


result2 = [Link]("(df.A + df.B) / (df.C - 1)")
[Link](result1, result2)
True
The [Link]() method allows much more succinct evaluation of expressions with the
columns:

result3 = [Link]('(A + B) / (C - 1)')


[Link](result1, result3)
True
Notice here that we treat column names as variables within the evaluated expression, and the
result is what we would wish.

Assignment in [Link]()
In addition to the options just discussed, [Link]() also allows assignment to any
column. Let's use the DataFrame from before, which has columns 'A', 'B', and 'C':

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

[Link]()
A B C
0 0.375506 0.406939 0.069938
1 0.069087 0.235615 0.154374
2 0.677945 0.433839 0.652324
3 0.264038 0.808055 0.347197
4 0.589161 0.252418 0.557789
We can use [Link]() to create a new column 'D' and assign to it a value computed from the
other columns:

[Link]('D = (A + B) / C', inplace=True)


[Link]()
A B C D
0 0.375506 0.406939 0.069938 11.187620
1 0.069087 0.235615 0.154374 1.973796
2 0.677945 0.433839 0.652324 1.704344
3 0.264038 0.808055 0.347197 3.087857
4 0.589161 0.252418 0.557789 1.508776
In the same way, any existing column can be modified:

[Link]('D = (A - B) / C', inplace=True)


[Link]()
A B C D
0 0.375506 0.406939 0.069938 -0.449425
1 0.069087 0.235615 0.154374 -1.078728
2 0.677945 0.433839 0.652324 0.374209
3 0.264038 0.808055 0.347197 -1.566886
4 0.589161 0.252418 0.557789 0.603708

Local variables in [Link]()


The [Link]() method supports an additional syntax that lets it work with local
Python variables. Consider the following:

column_mean = [Link](1)
result1 = df['A'] + column_mean
result2 = [Link]('A + @column_mean')
[Link](result1, result2)
True
The @ character here marks a variable name rather than a column name, and lets you
efficiently evaluate expressions involving the two "namespaces": the namespace of columns,

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

and the namespace of Python objects. Notice that this @ character is only supported by the
[Link]() method, not by the [Link]() function, because the [Link]()
function only has access to the one (Python) namespace.

[Link]() Method

The DataFrame has another method based on evaluated strings, called the query() method.
Consider the following:

result1 = df[(df.A < 0.5) & (df.B < 0.5)]


result2 = [Link]('df[(df.A < 0.5) & (df.B < 0.5)]')
[Link](result1, result2)
True
As with the example used in our discussion of [Link](), this is an expression involving
columns of the DataFrame. It cannot be expressed using the [Link]() syntax, however!
Instead, for this type of filtering operation, you can use the query() method:

result2 = [Link]('A < 0.5 and B < 0.5')


[Link](result1, result2)
True
In addition to being a more efficient computation, compared to the masking expression this is
much easier to read and understand. Note that the query() method also accepts the @ flag to
mark local variables:

Cmean = df['C'].mean()
result1 = df[(df.A < Cmean) & (df.B < Cmean)]
result2 = [Link]('A < @Cmean and B < @Cmean')
[Link](result1, result2)
True

Performance: When to Use These Functions


When considering whether to use these functions, there are two considerations: computation
time and memory use. Memory use is the most predictable aspect. As already mentioned, every
compound expression involving NumPy arrays or Pandas DataFrames will result in implicit
creation of temporary arrays: For example, this:

x = df[(df.A < 0.5) & (df.B < 0.5)]


Is roughly equivalent to this:
tmp1 = df.A < 0.5
tmp2 = df.B < 0.5

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

tmp3 = tmp1 & tmp2


x = df[tmp3]
If the size of the temporary DataFrames is significant compared to your available system
memory (typically several gigabytes) then it's a good idea to use an eval() or query()
expression. You can check the approximate size of your array in bytes using this:

[Link]
32000
On the performance side, eval() can be faster even when you are not maxing-out your system
memory.
The issue is how your temporary DataFrames compare to the size of the L1 or L2 CPU cache on
your system (typically a few megabytes in 2016); if they are much bigger, then eval() can avoid
some potentially slow movement of values between the different memory caches. The difference
in computation time between the traditional methods and the eval/query method is usually not
significant–if anything, the traditional method is faster for smaller arrays! The benefit of
eval/query is mainly in the saved memory, and the sometimes cleaner syntax they offer.
Key Differences:
[Link]()
Calculations, assignments, creating/modifying columns
DataFrame/Series with evaluated results (or modified in place)
Arithmetic, logical, and assignment expressions
[Link]()
Filtering rows based on conditions
New DataFrame with filtered rows
Conditional expressions (e.g., comparison, boolean)
When to Choose Which:
Use [Link]() when you need to perform calculations across columns or assign new values based
on expressions, and you want a concise, string-based syntax for these operations.
Use [Link]() when you need to select a subset of rows from your DataFrame based on one or
more conditions, and you prefer expressing these conditions as a string.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Data Visualization with MatPlotlib


Matplotlib is a powerful, cross-platform data visualization library in Python, built on NumPy and
designed to integrate with the SciPy ecosystem.
Created by John Hunter in 2002 and first released in 2003, it gained early momentum when
adopted by the Space Telescope Science Institute, which helped expand its capabilities.
A major strength of Matplotlib is its flexibility: it supports many operating systems, graphics
backends, and output formats, making it widely usable and reliable. This broad compatibility has
contributed to its large user and developer community, solidifying its position as a core tool in
scientific Python.
In recent years, Matplotlib’s interface has started to feel outdated compared to newer, more
modern visualization libraries like ggplot, ggvis, and web-based tools such as [Link]. However,
improvements such as customizable style sheets and the rise of higher-level wrappers—like
Seaborn, HoloViews, Altair, ggpy, and Pandas' own plotting—help modernize its usage.
Despite the emergence of these newer tools, Matplotlib remains essential due to its stability,
maturity, and low-level control. Even when using modern wrappers, understanding Matplotlib’s
core syntax is often necessary for fine-tuning visualizations. Therefore, it continues to be a
foundational component of the Python visualization ecosystem.

General Matplotlib Tips


Importing Matplotlib
import matplotlib as mpl
import [Link] as plt
While mpl refers to the overall Matplotlib package, the plt interface ([Link]) is the one
most frequently used for creating plots. It provides convenient functions for generating and
customizing visualizations, and will be used throughout plotting tasks.
Setting Styles
Matplotlib allows you to change the visual appearance of plots using style sheets. You can select
a style using the [Link]() directive. For example:
[Link]('classic')
This applies the classic Matplotlib look to all figures. Different styles can be chosen depending
on the desired aesthetics, and the style can be changed anytime during plotting.
Stylesheets are available in Matplotlib version 1.5 and later. Earlier versions support only the
default style.
show() or No show()? How to Display Your Plots
How you view Matplotlib plots depends on your working environment. The behavior and
recommended commands differ across three main contexts: scripts, the IPython shell, and
IPython notebooks.
Plotting from a Python Script:
Use [Link]() to display figures.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

It launches an event loop and opens interactive windows containing your plots.

import [Link] as plt


import numpy as np
x = [Link](0, 10, 100)
[Link](x, [Link](x))
[Link](x, [Link](x))
[Link]()
Run it via
$ python [Link]
Use [Link]() only once per session/script. Multiple calls can cause unpredictable behavior.

Plotting from an IPython Shell:


Enable Matplotlib mode using
%matplotlib
After this, any plotting command such as [Link]() will automatically open a figure window.
To force an update of an existing figure (if it doesn’t auto-refresh), use:
[Link]()
You typically do not need [Link]() in this mode.

Plotting in an IPython Notebook (Jupyter Notebook)


Enable Matplotlib with the %matplotlib magic command.
Two display options:
%matplotlib notebook → interactive plots embedded in the notebook.
%matplotlib inline → static PNG images embedded in the notebook.
For most documentation and teaching contexts, %matplotlib inline is preferred.
%matplotlib inline
import numpy as np
import [Link] as plt
x = [Link](0, 10, 100)
[Link](x, [Link](x))
[Link](x, [Link](x))

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Saving Figures to File


Matplotlib allows you to save plots in many different file formats using the savefig() function.
Saving a Figure
After creating a figure, save it using:
[Link]('my_figure.png')
This creates a file (e.g., my_figure.png) in the current working directory.
Viewing the Saved File
In IPython/Jupyter, you can display the saved image using:
from [Link] import Image
Image('my_figure.png')
File Format Selection
The file format is determined automatically from the filename’s extension.
Matplotlib supports many formats (depending on installed backends).
You can list available formats using:
[Link].get_supported_filetypes()
Example supported types include PNG, JPG, PDF, SVG, TIFF, EPS, and more.
Important Note
You do not need [Link]() in order to save a figure.
savefig() works independently of the display commands.
Two Interfaces for the Price of One
Matplotlib provides two different interfaces for creating plots:
1. MATLAB-style (state-based) interface using pyplot (plt)
2. Object-oriented (OO) interface using Figure and Axes objects
MATLAB-Style Interface (State-Based)
Designed for users familiar with MATLAB.
Functions like [Link](), [Link](), and [Link]() operate on a current figure and current
axes.
[Link]()

[Link](2, 1, 1)
[Link](x, [Link](x))

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

[Link](2, 1, 2)
[Link](x, [Link](x))
The interface is stateful—Matplotlib keeps track of:
Current figure → [Link]()
Current axes → [Link]()
Convenient for quick/simple plots but can become confusing in complex layouts (e.g., adding
elements to earlier subplots).

Object-Oriented Interface (Recommended for Complex Plots)


More explicit and powerful.
You manually create figure and axes objects and call plotting methods on them.
fig, ax = [Link](2)

ax[0].plot(x, [Link](x))
ax[1].plot(x, [Link](x))
Provides better control when creating detailed or multi-panel visualizations.
Avoids ambiguity of “current” figure/axes.
Choosing Between the Two
For simple plots → either style works.
For multi-plot figures, complex layouts, or professional-quality visualizations → the object-
oriented interface is preferred.
In many cases, switching is as simple as replacing [Link]() with [Link]().

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Simple Line Plots


[Link]() — Plotting Lines or Markers
Syntax
[Link](x, y)
Common Extended Syntax
[Link](x, y, format_string, linewidth=value, color='color', label='name')
Parameters
 x → x-axis data
 y → y-axis data
 format_string → optional shorthand:
o 'r--' → red dashed line
o 'bo' → blue circle markers
 linewidth= or lw= → thickness
 color= → explicit color
 label= → name to show in legend
Example
[Link](x, [Link](x), 'r--', label='sin curve')

[Link]() — Set or Get Axis Limits


Syntax
[Link]()
Returns current axis limits.
Set axis limits with 4 values
[Link]([xmin, xmax, ymin, ymax])
Special mode strings
[Link]('tight') # fits data tightly
[Link]('equal') # equal scaling on both axes
Example
[Link]([0, 10, -1.5, 1.5])

[Link]() — Display Legend


Syntax
[Link]()
Common extended syntax
[Link](loc='location_name')
Important:
Legend will only show labels if you used label= inside [Link]().
Location options (loc)
 'upper left'
 'upper right'

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

 'lower left'
 'lower right'
 'best' (automatically chooses best position)
Example
[Link](x, [Link](x), label='Sine')
[Link](x, [Link](x), label='Cosine')
[Link](loc='upper right')

To set up the notebook for plotting and importing the packages we will use:
%matplotlib inline
import [Link] as plt
[Link]('seaborn-whitegrid')
import numpy as np
For all Matplotlib plots, start by creating a figure and an axes.
In their simplest form, a figure and axes can be created as follows:
fig = [Link]()
ax = [Link]()

The figure (an instance of the class [Link]) can be thought of as a single container that
contains all the objects representing axes, graphics, text, and labels. It does not create any axes
by itself—just a blank canvas.
The axes (an instance of the class [Link]) is what we see above: a bounding box with ticks and
labels, which will eventually contain the plot elements that make up our visualization.

Use the [Link] function to plot some data. Let's start with a simple sinusoid:

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

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

[Link] is a numPy function that generates an array of 1000 evenly spaced values between 0
and 10 (including both endpoints).
[Link](start, stop, num)
start = 0 → starting value
stop = 10 → ending value
num = 1000 → number of points
x = [0.0, 0.01001, 0.02002, 0.03003, ..., 10.0]

It is used because it creates a smooth, continuous range of x-values, perfect for plotting functions
like:
[Link](x, [Link](x))
The large number of points (1000) gives smooth curves.

Alternatively, we can use the pylab interface and let the figure and axes be created for us in the
background
[Link](x, [Link](x))

If we want to create a single figure with multiple lines, we can simply call the plot function
multiple times:

[Link](x, [Link](x))
[Link](x, [Link](x))

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Adjusting the Plot: Line Colors and Styles


The [Link]() function takes additional arguments that can be used to specify these. To adjust the
color, you can use the color keyword, which accepts a string argument representing virtually any
imaginable color. If no color is specified, Matplotlib will automatically cycle through a set of
default colors for multiple lines. The color can be specified in a variety of ways:
[Link](x, [Link](x - 0), color='blue') # specify color by name
[Link](x, [Link](x - 1), color='g') # short color code (rgbcmyk)
[Link](x, [Link](x - 2), color='0.75') # Grayscale between 0 and 1
[Link](x, [Link](x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF)
[Link](x, [Link](x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 to 1
[Link](x, [Link](x - 5), color='chartreuse'); # all HTML color names supported

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The line style can be adjusted using the linestyle keyword:


[Link](x, x + 0, linestyle='solid')
[Link](x, x + 1, linestyle='dashed')
[Link](x, x + 2, linestyle='dashdot')
[Link](x, x + 3, linestyle='dotted');
# For short, you can use the following codes:
[Link](x, x + 4, linestyle='-') # solid
[Link](x, x + 5, linestyle='--') # dashed
[Link](x, x + 6, linestyle='-.') # dashdot
[Link](x, x + 7, linestyle=':'); # dotted

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

These linestyle and color codes can be combined into a single non-keyword argument to
the [Link]() function:
[Link](x, x + 0, '-g') # solid green
[Link](x, x + 1, '--c') # dashed cyan
[Link](x, x + 2, '-.k') # dashdot black
[Link](x, x + 3, ':r'); # dotted red

These single-character color codes reflect the standard abbreviations in the RGB
(Red/Green/Blue) and CMYK (Cyan/Magenta/Yellow/blacK) color systems, commonly used for
digital color graphics.
Adjusting the Plot: Axes Limits
Matplotlib does a decent job of choosing default axes limits for your plot, but sometimes it's nice
to have finer control. The most basic way to adjust axis limits is to use the [Link]() and
[Link]() methods:
[Link](x, [Link](x))

[Link](-1, 11)
[Link](-1.5, 1.5);

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

If for some reason you'd like either axis to be displayed in reverse, you can simply reverse the
order of the arguments:
[Link](x, [Link](x))

[Link](10, 0)
[Link](1.2, -1.2);

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The [Link]() method allows you to set the x and y limits with a single call, by passing a list
which specifies [xmin, xmax, ymin, ymax]:
[Link](x, [Link](x))
[Link]([-1, 11, -1.5, 1.5]);

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The [Link]() method goes even beyond this, allowing you to do things like automatically tighten
the bounds around the current plot:
[Link](x, [Link](x))
[Link]('tight');

It allows even higher-level specifications, such as ensuring an equal aspect ratio so that on your
screen, one unit in x is equal to one unit in y:
[Link](x, [Link](x))
[Link]('equal');

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Labeling Plots
Labeling of plots: titles, axis labels, and simple legends.
Titles and axis labels are the simplest such labels—there are methods that can be used to quickly
set them. The position, size, and style of these labels can be adjusted using optional arguments to
the function:
[Link](x, [Link](x))
[Link]("A Sine Curve")
[Link]("x")
[Link]("sin(x)");

When multiple lines are being shown within a single axes, it can be useful to create a plot legend
that labels each line type. It is done via the [Link]() method. Specify the label of each line
using the label keyword of the plot function:
[Link](x, [Link](x), '-g', label='sin(x)')
[Link](x, [Link](x), ':b', label='cos(x)')
[Link]('equal')

[Link]();
The [Link]() function keeps track of the line style and color, and matches these with the
correct label.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

While most plt functions translate directly to ax methods (such


as [Link]() → [Link](), [Link]() → [Link](), etc.), this is not the case for all
commands. I
n particular, functions to set limits, labels, and titles are slightly modified.
For transitioning between MATLAB-style functions and object-oriented methods, make
the following changes:
 [Link]() → ax.set_xlabel()
 [Link]() → ax.set_ylabel()
 [Link]() → ax.set_xlim()
 [Link]() → ax.set_ylim()
 [Link]() → ax.set_title()
In the object-oriented interface to plotting, rather than calling these functions
individually, it is often more convenient to use the [Link]() method to set all these
properties at once:
ax = [Link]()
[Link](x, [Link](x))
[Link](xlim=(0, 10), ylim=(-2, 2),
xlabel='x', ylabel='sin(x)',
title='A Simple Plot');

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Simple Scatter Plots


Instead of points being joined by line segments, here the points are represented individually with
a dot, circle, or other shape.
%matplotlib inline
import [Link] as plt
[Link]('seaborn-whitegrid')
import numpy as np
Scatter Plots with [Link]
[Link]/[Link] function can produce scatter plots as well:
x = [Link](0, 10, 30)
y = [Link](x)

[Link](x, y, 'o', color='black');

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The third argument in the function call is a character that represents the type of symbol used for
the plotting. Just as you can specify options such as '-', '--' to control the line style, the marker
style has its own set of short string codes. Most of the possibilities are fairly intuitive, and we'll
show a number of the more common ones here:
rng = [Link](0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
[Link]([Link](5), [Link](5), marker,
label="marker='{0}'".format(marker))
[Link](numpoints=1)
[Link](0, 1.8);

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

For even more possibilities, these character codes can be used together with line and
color codes to plot points along with a line connecting them:
[Link](x, y, '-ok');

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Additional keyword arguments to [Link] specify a wide range of properties of the lines
and markers:
[Link](x, y, '-p', color='gray',
markersize=15, linewidth=4,
markerfacecolor='white',
markeredgecolor='gray',
markeredgewidth=2)
[Link](-1.2, 1.2);

Scatter Plots with [Link]


A second, more powerful method of creating scatter plots is the [Link] function, which can be
used very similarly to the [Link] function:
[Link](x, y, marker='o');

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The primary difference of [Link] from [Link] is that it can be used to create scatter plots
where the properties of each individual point (size, face color, edge color, etc.) can be
individually controlled or mapped to data.
A random scatter plot with points of many colors and sizes. In order to better see the overlapping
results, alpha keyword is used to adjust the transparency level:
rng = [Link](0)
x = [Link](100)
y = [Link](100)
colors = [Link](100)
sizes = 1000 * [Link](100)

[Link](x, y, c=colors, s=sizes, alpha=0.3,


cmap='viridis')
[Link](); # show color scale

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

The color argument is automatically mapped to a color scale, and that the size argument is given
in pixels. The color and size of points can be used to convey information in the visualization, in
order to visualize multidimensional data.
For example, the Iris data from Scikit-Learn, where each sample is one of three types of flowers
that has had the size of its petals and sepals carefully measured:
 features[0] → sepal length (150 values)
 features[1] → sepal width
 features[2] → petal length
 features[3] → petal width

from [Link] import load_iris


iris = load_iris()
features = [Link].T

[Link](features[0], features[1], alpha=0.2,


s=100*features[3], c=[Link], cmap='viridis')
[Link](iris.feature_names[0])
[Link](iris.feature_names[1]);

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

This scatter plot has given us the ability to simultaneously explore four different dimensions of
the data: the (x, y) location of each point corresponds to the sepal length and width, the size of
the point is related to the petal width, and the color is related to the particular species of flower.
Multicolor and multifeature scatter plots like this can be useful for both exploration and
presentation of data.
plot Versus scatter: A Note on Efficiency
When plotting small datasets, both [Link]() and [Link]() work fine.
But when the dataset becomes large (thousands or millions of points), there is an important
performance difference.
Why [Link]() is Faster
[Link]() handles each point individually
[Link]() allows every point to have:
its own color
its own size
its own marker
Because of this flexibility, Matplotlib must draw each point separately.
For thousands of points, this becomes slow.
Example work done by renderer:
“Draw point 1 with size A and color X… draw point 2 with size B and color Y… draw point
3…, etc.”

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

[Link]() draws all points the same way


All points share:
the same color
the same size
the same marker style
Since they are identical, Matplotlib calculates the appearance once and simply "clones" it for all
points.
This makes drawing much faster.
Example work done by renderer:
“Here is the style → apply it to all points at once.”
Performance Difference
With small datasets → little difference
With large datasets → huge difference
Scatter plot → slow
Line plot or point-plot using [Link]() → fast

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Question 2:
Multidimensional Visualization using the Iris Dataset
The Iris dataset contains measurements of petals and sepals for three different
species of flowers. Each record consists of four features — sepal length, sepal
width, petal length, and petal width — along with the species type.
Task:
Visualize four dimensions of the Iris dataset using a scatter plot where:
The x-axis represents sepal length
The y-axis represents sepal width
The size of each point represents petal width
The color of each point represents the species type
Instructions:
Load the Iris dataset using load_iris() from [Link].
Extract the feature matrix and target values.
Use [Link]() to create the scatter plot.
Use the 'viridis' colormap to distinguish different flower species.
Add axis labels (Sepal Length, Sepal Width) and a color bar for better
interpretation.
Add an appropriate title (e.g., “Iris Dataset: Multidimensional Visualization”).
Expected Output:
A scatter plot where:
Each flower species is represented by a different color.
The position of points shows sepal length and width.
The size of points shows petal width.
The plot helps in understanding the pattern and separation among flower species.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Visualization with Seaborn

Introduction: Why Seaborn?


Matplotlib is powerful but has limitations that make high-level data visualization cumbersome.
Limitations of Matplotlib:
1. Outdated defaults (pre-v2.0):
o Based on MATLAB (circa 1999).
o Poor color schemes and design defaults.
2. Low-level API:
o Complex statistical plots require lengthy boilerplate code.
3. Weak Pandas integration:
o Not designed for DataFrame objects.
o Must manually extract and merge Series for plotting.
Solution: Seaborn
Seaborn is a high-level plotting library built on top of Matplotlib, offering:
 Better default aesthetics (style, color, layout).
 Simplified functions for common statistical visualizations.
 Native Pandas integration (directly plots using DataFrame labels).
 Support for regression, distribution, and categorical plots.
Even though Matplotlib 2.0+ has improved with new styles and DataFrame support, Seaborn
remains a more elegant and efficient option.

Seaborn vs Matplotlib — Visual Comparison


Example: Random Walk

Using Matplotlib
import [Link] as plt
[Link]('classic')
%matplotlib inline
import numpy as np, pandas as pd

# Create random walk data


rng = [Link](0)
x = [Link](0, 10, 500)
y = [Link]([Link](500, 6), 0)

# Plot
[Link](x, y)
[Link]('ABCDEF', ncol=2, loc='upper left')
Output: Functional but visually outdated and cluttered.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Using Seaborn
import seaborn as sns
[Link]() # apply Seaborn theme

[Link](x, y)
[Link]('ABCDEF', ncol=2, loc='upper left')
Output: Modern, cleaner, and aesthetically pleasing.
Seaborn modifies Matplotlib’s defaults and enhances visuals without changing plotting logic.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Exploring Seaborn Plot Types


Seaborn provides high-level commands for statistical and exploratory visualization.
All plots can be done with Matplotlib, but Seaborn offers more intuitive APIs.

A. Histograms, KDE, and Densities

Used to visualize distributions of single or multiple variables.

data = [Link].multivariate_normal([0, 0], [[5, 2], [2, 2]], 2000)


data = [Link](data, columns=['x', 'y'])

Using Matplotlib:
for col in 'xy':
[Link](data[col], normed=True, alpha=0.5)

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Using Seaborn:

Kernel Density Estimation (KDE):

for col in 'xy':


[Link](data[col], shade=True)

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Histogram + KDE (Combined):

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

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

(Now replaced by [Link]/[Link] in new versions)

2D KDE:

[Link](data)

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Joint Distribution Plot:

Displays both marginal and joint distributions.

with sns.axes_style('white'):
[Link]("x", "y", data, kind='kde') # smooth KDE view

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Alternative:

[Link]("x", "y", data, kind='hex') # hexbin plot

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

B. Pair Plots (Pairwise Relationships)

Used to explore correlations among multidimensional data.

Displays scatter plots between every pair of features + histograms on diagonals.

Example (Iris Dataset)


iris = sns.load_dataset("iris")
[Link](iris, hue='species', size=2.5)

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Highlights:

Color (hue) separates species.

Quickly shows feature relationships.

C. Faceted Histograms (FacetGrid)

Used to visualize subsets of data by categories.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Example (Tips Dataset)


tips = sns.load_dataset('tips')
tips['tip_pct'] = 100 * tips['tip'] / tips['total_bill']

grid = [Link](tips, row="sex", col="time", margin_titles=True)


[Link]([Link], "tip_pct", bins=[Link](0, 40, 15))

Shows how tip percentage distribution varies by gender and meal time.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

D. Factor Plots (Categorical Comparisons)

Used for visualizing how a numerical variable varies across categorical variables.

with sns.axes_style('ticks'):
g = [Link]("day", "total_bill", "sex", data=tips, kind="box")
g.set_axis_labels("Day", "Total Bill")

Displays:

Daily total bill distribution.

Gender-wise variation.

(In newer versions, use [Link]() instead of factorplot().)

E. Joint Distributions

Revisited to visualize relationships between two numeric variables and their distributions.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Example (Tips Dataset)


with sns.axes_style('white'):
[Link]("total_bill", "tip", data=tips, kind='hex') # Hexbin

or

[Link]("total_bill", "tip", data=tips, kind='reg') # Regression line

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Shows both relationship & trend fitting.

F. Bar Plots / Count Plots (Time Series or Categorical Counts)

Used for count-based or temporal analysis.

Example (Planets Dataset)


planets = sns.load_dataset('planets')

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

with sns.axes_style('white'):
g = [Link]("year", data=planets, aspect=2, kind="count", color='steelblue')
g.set_xticklabels(step=5)

Shows number of planets discovered per year.

Add Hue (by Discovery Method)


with sns.axes_style('white'):
g = [Link]("year", data=planets, aspect=4.0,
kind='count', hue='method', order=range(2001, 2015))
g.set_ylabels('Number of Planets Discovered')

Displays yearly discoveries categorized by method.

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555
ACHARYA INSTITUTE OF TECHNOLOGY
Affiliated to Visvesvaraya Technological University, Belagavi, Govt. of Karnataka.
Approved by AICTE, New Delhi and Accredited by NBA (AE, BT, CSE, ECE, ME and MTE)
Department of Artificial Intelligence & Machine Learning

Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555

You might also like