0% found this document useful (0 votes)
0 views42 pages

AI Lab Slides(Matplotlib) (1)

Matplotlib is a powerful open-source plotting library for Python, widely used for data visualization with NumPy and Pandas. It provides various plotting capabilities through its Pyplot module, allowing users to create different types of graphs such as line, bar, scatter, and histograms with ease. The document also covers installation instructions, general components of Matplotlib figures, and examples of plotting with both NumPy and Pandas.

Uploaded by

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

AI Lab Slides(Matplotlib) (1)

Matplotlib is a powerful open-source plotting library for Python, widely used for data visualization with NumPy and Pandas. It provides various plotting capabilities through its Pyplot module, allowing users to create different types of graphs such as line, bar, scatter, and histograms with ease. The document also covers installation instructions, general components of Matplotlib figures, and examples of plotting with both NumPy and Pandas.

Uploaded by

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

Programming for AI

Matplotlib
Matplotlib
What is Matplotlib?

● To make necessary statistical inferences, it becomes necessary to visualize your data


and Matplotlib is one such solution for the Python users.
● It is a very powerful plotting library useful for those working with Python and
NumPy, Pandas.
● The most used module of Matplotib is Pyplot which provides an interface like
MATLAB but instead, it uses Python and it is open source.
Install Matplotlib?

pip install matplotlib


conda install matplotlib

● Matplotlib is an open-source drawing library that supports various drawing types


● You can generate plots, histograms, bar charts, and other types of charts with just
a few lines of code
● It’s often used in web application servers, shells, and Python scripts, for data
analysis, insights
PyPlot

● Pyplot is a Matplotlib module that provides simple functions for adding plot elements,
such as lines, images, text, etc. to the axes in the current figure.
● It emphasizes interactivity, enabling users to interact with the charts by zooming,
panning, hovering over data points for information, and more. This makes it
particularly useful for exploratory data analysis and presentations.
● It is available in several programming languages, including Python, R, JavaScript,
Julia, and MATLAB. This makes it accessible to a broad community of data analysts
and scientists.
General Components

● A Matplotlib figure can be categorized into several parts as below:


○ Figure: It is a whole figure which may contain one or more than one axes (plots). You can
think of a Figure as a canvas which contains plots.
○ Axes: It is what we generally think of as a plot. A Figure can contain many Axes. It contains
two or three (in the case of 3D) Axis objects. Each Axes has a title, an x-label and a y-label.
○ Axis: They are the number line like objects and take care of generating the graph limits.
○ Artist: Everything which one can see on the figure is an artist like Text objects, Line2D
objects, collection objects. Most Artists are tied to Axes.
Matplotlib with Numpy
Plotting

● Here we import Matplotlib’s Pyplot


module and Numpy library as most of
the data that we will be working with
will be in the form of arrays only.
● We pass two arrays as our input
arguments to Pyplot’s plot() method,
which is line by default, and use
show() method to invoke the required
plot.
Plotting

● Here note that the first array appears


on the x-axis and second array appears
on the y-axis of the plot. Now that our
first plot is ready, let us add the title,
and name x-axis and y-axis using
methods title(), xlabel() and ylabel()
respectively.
Plotting

● We can also specify the


size of the figure using
method figure() and
passing the values as a
tuple of the length of rows
and columns to the
argument
Plotting

● With every X and Y argument, you can also pass an optional third argument in the
form of a string which indicates the colour and line type of the plot.
● The default format is b- which means a solid blue line.
● In the figure coming next, we use go which means green circles. Likewise, we can
make many such combinations to format our plot.
Plotting
Plotting

● We can also plot multiple sets of


data by passing in multiple sets of
arguments of X and Y axis in the
plot() method as shown.
Plotting
● We can use subplot() method to add more than one plots in one figure.
● In the image coming next, we used this method to separate two graphs which we
plotted on the same axes in the previous example.
● The subplot() method takes three arguments: they are nrows, ncols and index. They
indicate the number of rows, number of columns and the index number of the
sub-plot.
● For instance, in our example, we want to create two sub-plots in one figure such that it
comes in one row and in two columns and hence we pass arguments (1,2,1) and
(1,2,2) in the subplot() method.
● Note that we have separately used title() method for both subplots. We use suptitle()
method to make a centralized title for the figure.
Plotting
Plotting

● If we want our sub-plots in two


rows and single column, we can
pass arguments (2,1,1) and
(2,1,2)
Plotting
● The discussed way of creating subplots becomes a bit tedious when we want many
subplots in our figure.
● A more convenient way is to use subpltots() method. Notice the difference of ‘s’ in
both the methods.
● This method takes two arguments nrows and ncols as number of rows and number of
columns respectively.
● This method creates two objects:figure and axes which we store in variables fig and ax
which can be used to change the figure and axes level attributes respectively. Note that
these variable names are chosen arbitrarily.
Plotting
Types of Graphs
● A variety of graphs and charts are available in PyPlot

● Line, Scatter, Bar, Histogram, Box, Pie, Heatmap, Contour, 3D, Animations, Gantt
Charts, Geo Maps

● For categorical variables utilize Bar Charts and Boxplots.

● For continuous variables utilize Histograms, Scatterplots, Line graphs, and Boxplots.
Bar Graphs
● Bar graphs are one of the most
common types of graphs and are used
to show data associated with the
categorical variables.
● Pyplot provides a method bar() to
make bar graphs which take
arguments: categorical variables, their
values and color (if you want to
specify any).
Bar Graphs
● To make horizontal bar graphs use
method barh().
● Also we can pass an argument (with its
value) xerr or yerr (in case of the
above vertical bar graphs) to depict the
variance in our data as follows:
Bar Graphs
● To create horizontally stacked bar graphs we use the bar() method twice and pass the
arguments where we mention the index and width of our bar graphs in order to
horizontally stack them together.

● Also, notice the use of two other methods legend() which is used to show the legend
of the graph and xticks() to label our x-axis based on the position of our bars.
Bar Graphs
Bar Graphs
● Similarly, to vertically
stack the bar graphs
together, we can use an
argument bottom and
mention the bar graph
which we want to stack
below as its value.
Pie Charts
● One more basic type of chart is a
Pie chart which can be made using
the method pie() We can also pass
in arguments to customize our Pie
chart to show shadow, explode a
part of it, tilt it at an angle as
follows:
Histograms
● Histograms are a very common type of plots when we are looking at data like height and
weight, stock prices, waiting time for a customer, etc which are continuous in nature
● Histogram’s data is plotted within a range against its frequency. Histograms are very
commonly occurring graphs in probability and statistics and form the basis for various
distributions like the normal -distribution, t-distribution, etc.
Histograms
● In this example, we generate a random
continuous data of 1000 entries and plot it
against its frequency with the data divided
into 10 equal strata.
● We have used NumPy’s [Link]()
method which generates data with the
properties of a standard normal distribution
i.e. mean = 0 and standard deviation = 1, and
hence the histogram looks like a normal
distribution curve.
Scatter and 3D Plots
● Scatter plots are widely used graphs,
especially they come in handy in
visualizing a problem of regression.
● In this example, we feed in arbitrarily
created data of height and weight and plot
them against each other. We used xlim()
and ylim() methods to set the limits of
X-axis and Y-axis respectively.
Scatter and 3D Plots
● The above scatter can also be visualized in three dimensions. To use this functionality,
we first import the module mplot3d as follows:

from mpl_toolkits import mplot3d

● Once the module is imported, a three-dimensional axes is created by passing the keyword
projection='3d' to the axes() method of Pyplot module. Once the object instance is
created, we pass our arguments height and weight to scatter3D() method.
Scatter and 3D Plots
Scatter and 3D Plots
● We can also create 3-D graphs of
other types like line graph, surface,
wireframes, contours, etc.
● The previous example in the form
of a simple line graph is as
follows: Here instead of
scatter3D() we use method
plot3D()
Matplotlib with Pandas
Pandas
● Our Data from previous lecture, the
IMDb Movies data
Pandas – Scatter Plot
● Let's plot the relationship between ratings and revenue. All we need to do is call
.plot() on movies_df with some info about how to construct the plot:

movies_df.plot(kind='scatter', x='rating', y='revenue_millions',


title='Revenue (millions) vs Rating');
Pandas – Scatter Plot
Pandas - Histogram
● If we want to plot a simple Histogram
based on a single column, we can call
plot on a column:

● movies_df['rating'].plot(kind
='hist', title='Rating’);
Pandas
● Do you remember the .describe()
example from the last lecture? Well,
there's a graphical representation of the
interquartile range, called the Boxplot.
● Let's recall what describe() gives us on
the ratings column:

movies_df['rating'].describe()
Pandas - Boxplot
● Using a Boxplot we can visualize
this data:

● movies_df['rating'].plot(
kind="box")
Pandas - Boxplot
● Boxplot Information
Pandas - Boxplot
● By combining categorical and
continuous data, we can create a
Boxplot of revenue that is grouped by
the Rating Category we created above:

● movies_df.boxplot(column='r
evenue_millions',
by='rating_category');
More Matplotlib?
● For more plots with Pandas, visit this Article
● More Examples and Details, checkout from this source Article
● Or, better yet, study on the actual documentation at Matplotlib Docs
Acknowledgment!
This presentation contains various contents from different books, lecture notes,
and the web. These solely belong to their owners and are here used only for
clarifying various educational concepts. Any copyright infringement is not
intended.

You might also like