Unit 5 Maplotlib 2
Unit 5 Maplotlib 2
allows you to create and share documents that contain live code,
equations, visualizations and narrative text.
Uses include data cleaning and transformation, numerical
simulation, statistical modeling, data visualization, machine
learning, and much more.
Table Of Content
Getting Started
Pyplot
Figure class
Axes Class
Setting Limits and Tick labels
Multiple Plots
What is a Legend?
Creating Different Types of Plots
Line Graph
Bar chart
Histograms
Scatter Plot
Pie Chart
3D Plots
Working with Images
Customizing Plots in Matplotlib
More articles on Matplotlib
Exercises, Applications, and Projects
Output:
In the above example, the elements of X and Y provides the coordinates for the x axis
and y axis and a straight line is plotted against those coordinates.
Pyplot
Pyplot is a Matplotlib module that provides a MATLAB-like interface. Pyplot
provides functions that interact with the figure i.e. creates a figure, decorates the plot
with labels, and creates a plotting area in a figure.
Example:
# Python program to show pyplot module
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.axis([0, 6, 0, 20])
plt.show()
Output:
Matplotlib take care of the creation of inbuilt defaults like Figure and Axes.
Figure: This class is the top-level container for all the plots means it is the
overall window or page on which everything is drawn. A figure object can be
considered as a box-like container that can hold one or more axes.
Axes: This class is the most basic and flexible component for creating sub-
plots. You might confuse axes as the plural of axis but it is an individual plot or
graph. A given figure may contain many axes but given axes can only be in one
figure.
Figure class
Figure class is the top-level container that contains one or more axes. It is the overall
window or page on which everything is drawn.
Syntax:
class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None,
edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None,
tight_layout=None, constrained_layout=None)
Example 1:
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
Output:
Example 2: Creating multiple plots
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
plt.show()
Output:
Axes Class
Axes class is the most basic and flexible unit for creating sub-plots. A given figure
may contain many axes, but a given axes can only be present in one figure. The axes()
function creates the axes object. Let’s see the below example.
Syntax:
matplotlib.pyplot.axis(*args, emit=True, **kwargs)
Example 1:
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
# Creating the axes object with argument as [left, bottom, width,
height]
ax = plt.axes([1, 1, 1, 1])
Output:
Example 2:
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
fig = plt.figure(figsize = (5, 4))
Output:
Setting Limits and Tick labels
You might have seen that Matplotlib automatically sets the values and the
markers(points) of the x and y axis, however, it is possible to set the limit and markers
manually. set_xlim() and set_ylim() functions are used to set the limits of the x-axis
and y-axis respectively. Similarly, set_xticklabels() and set_yticklabels() functions
are used to set tick labels.
Example:
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
x = [3, 1, 3]
y = [3, 2, 1]
Output:
Multiple Plots
Till now you must have got a basic idea about Matplotlib and plotting some simple
plots, now what if you want to plot multiple plots in the same figure. This can be done
using multiple ways. One way was discussed above using the add_axes() method of
the figure class. Let’s see various ways multiple plots can be added with the help of
examples.
Method 1: Using the add_axes() method
The add_axes() method figure module of matplotlib library is used to add an axes to
the figure.
Syntax:
add_axes(self, *args, **kwargs)
Example:
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
Output:
The add_axes() method adds the plot in the same figure by creating another axes
object.
Method 2: Using subplot() method.
This method adds another plot to the current figure at the specified grid position.
Syntax:
subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(ax)
Example:
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
z = [1, 3, 1]
Output:
Output:
A Legend can be created using the legend() method. The attribute Loc in the legend()
is used to specify the location of the legend. The default value of loc is loc=”best”
(upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the
legend at the corresponding corner of the axes/figure.
The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the
coordinates of the legend, and the attribute ncol represents the number of columns that
the legend has. Its default value is 1.
Syntax:
matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)
Example:
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
plt.plot(x, y)
plt.plot(y, x)
Output:
Refer to the below articles to get detailed information about the legend –
Matplotlib.pyplot.legend() in Python
Matplotlib.axes.Axes.legend() in Python
Change the legend position in Matplotlib
How to Change Legend Font Size in Matplotlib?
How Change the vertical spacing between legend entries in Matplotlib?
Use multiple columns in a Matplotlib legend
How to Create a Single Legend for All Subplots in Matplotlib?
How to manually add a legend with a color box on a Matplotlib figure ?
How to Place Legend Outside of the Plot in Matplotlib?
How to Remove the Legend in Matplotlib?
Remove the legend border in Matplotlib
Creating Different Types of Plots
Line Graph
Till now you all must have seen that we are working with only the line charts as they
are easy to plot and understand. Line Chart is used to represent a relationship between
two data X and Y on a different axis. It is plotted using the pot() function. Let’s see
the below example
Example:
Python3
Output:
Refer to the below article to get detailed information about line chart.
Line chart in Matplotlib
Line plot styles in Matplotlib
Plot a Horizontal line in Matplotlib
Plot a Vertical line in Matplotlib
Plot Multiple lines in Matplotlib
Change the line opacity in Matplotlib
Increase the thickness of a line with Matplotlib
Plot line graph from NumPy array
How to Fill Between Multiple Lines in Matplotlib?
Bar chart
A bar plot or bar chart is a graph that represents the category of data with rectangular
bars with lengths and heights that is proportional to the values which they represent.
The bar plots can be plotted horizontally or vertically. A bar chart describes the
comparisons between the discrete categories. It can be created using the bar() method.
Syntax:
plt.bar(x, height, width, bottom, align)
Example:
Python3
Output:
Refer to the below articles to get detailed information about Bar charts –
Bar Plot in Matplotlib
Draw a horizontal bar chart with Matplotlib
Create a stacked bar plot in Matplotlib
Stacked Percentage Bar Plot In MatPlotLib
Plotting back-to-back bar charts Matplotlib
How to display the value of each bar in a bar chart using Matplotlib?
How To Annotate Bars in Barplot with Matplotlib in Python?
How to Annotate Bars in Grouped Barplot in Python?
Histograms
Output:
Refer to the below articles to get detailed information about histograms.
Plotting Histogram in Python using Matplotlib
Create a cumulative histogram in Matplotlib
How to plot two histograms together in Matplotlib?
Overlapping Histograms with Matplotlib in Python
Bin Size in Matplotlib Histogram
Compute the histogram of a set of data using NumPy in Python
Plot 2-D Histogram in Python using Matplotlib
Scatter Plot
Scatter plots are used to observe the relationship between variables and use dots to
represent the relationship between them. The scatter() method in the matplotlib
library is used to draw a scatter plot.
Syntax:
matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None,
cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None,
edgecolors=None)
Example:
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
Output:
Refer to the below articles to get detailed information about the scatter plot.
matplotlib.pyplot.scatter() in Python
How to add a legend to a scatter plot in Matplotlib ?
How to Connect Scatterplot Points With Line in Matplotlib?
How to create a Scatter Plot with several colors in Matplotlib?
How to increase the size of scatter points in Matplotlib ?
Pie Chart
A Pie Chart is a circular statistical plot that can display only one series of data. The
area of the chart is the total percentage of the given data. The area of slices of the pie
represents the percentage of the parts of the data. The slices of pie are called wedges.
The area of the wedge is determined by the length of the arc of the wedge. It can be
created using the pie() method.
Syntax:
matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None,
autopct=None, shadow=False)
Example:
import matplotlib.pyplot as plt
# data to display on plots
x = [1, 2, 3, 4]
Output:
Refer to the below articles to get detailed information about pie charts.
matplotlib.axes.Axes.pie() in Python
Plot a pie chart in Python using Matplotlib
How to set border for wedges in Matplotlib pie chart?
Radially displace pie chart wedge in Matplotlib
3D Plots
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the
time when the release of 1.0 occurred, the 3D utilities were developed upon the 2D
and thus, we have a 3D implementation of data available today.
Example:
import matplotlib.pyplot as plt
# Creating the figure object
fig = plt.figure()
Output:
The above code lets the creation of a 3D plot in Matplotlib. We can create different
types of 3D plots like scatter plots, contour plots, surface plots, etc. Let’s create a
simple 3D line plot.
Example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
z = [1, 8, 27, 64, 125]
# Creating the figure object
fig = plt.figure()
# keeping the projection = 3d
# creates the 3d plot
ax = plt.axes(projection = '3d')
ax.plot3D(z, y, x)
Output:
Refer to the below articles to get detailed information about 3D plots.
Three-dimensional Plotting in Python using Matplotlib
3D Scatter Plotting in Python using Matplotlib
3D Surface plotting in Python using Matplotlib
3D Wireframe plotting in Python using Matplotlib
3D Contour Plotting in Python using Matplotlib
Tri-Surface Plot in Python using Matplotlib
Surface plots and Contour plots in Python
How to change angle of 3D plot in Python?
How to animate 3D Graph using Matplotlib?
Draw contours on an unstructured triangular grid in Python using
Matplotlib
Working with Images
The image module in matplotlib library is used for working with images in Python.
The image module also includes two useful methods which are imread which is used
to read images and imshow which is used to display the image.
Example:
# importing required libraries
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading the image
testImage = img.imread('g4g.png')
# displaying the image
plt.imshow(testImage)
Output: