Notes
Notes
MODULE 3
Then:
goog = goog['Close']
[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
Difference
resample() → summarizes data (aggregation)
asfreq() → just picks existing data points (selection)
[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
Visualization:
The plot shows original, shifted, and index-shifted series.
The difference is clear — shift() displaces values, tshift() moves time labels.
This shows percentage growth of Google stock over a rolling one-year window.
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)
Interpretation:
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
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
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:
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.
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:
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
As of Pandas v0.16, [Link]() supports a wide range of operations. To demonstrate these, we'll
use the following integer DataFrames:
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:
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.
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:
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:
Cmean = df['C'].mean()
result1 = df[(df.A < Cmean) & (df.B < Cmean)]
result2 = [Link]('A < @Cmean and B < @Cmean')
[Link](result1, result2)
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
[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
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.
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, 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).
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
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
[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
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
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
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
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);
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)
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
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
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
Using Matplotlib
import [Link] as plt
[Link]('classic')
%matplotlib inline
import numpy as np, pandas as pd
# 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
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:
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](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
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
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:
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
Highlights:
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 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
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:
Gender-wise variation.
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
or
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
with sns.axes_style('white'):
g = [Link]("year", data=planets, aspect=2, kind="count", color='steelblue')
g.set_xticklabels(step=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
Acharya Dr. Sarvepalli Radhakrishnan Road, Soladevanahalli, ACHIT Nagar P. O., Bangalore-560 107
[Link] Ph.: 080 22555555