0% found this document useful (0 votes)
6 views27 pages

Only Matplotlib

Matplotlib is a powerful Python library for creating 2D plots and visualizations, built on NumPy and designed for use with the SciPy stack. It offers various plotting functions such as line, bar, scatter, and histogram, and can be utilized in scripts, shells, and web applications. The library includes a Pyplot module that provides a MATLAB-like interface for easy plotting and customization of visualizations.

Uploaded by

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

Only Matplotlib

Matplotlib is a powerful Python library for creating 2D plots and visualizations, built on NumPy and designed for use with the SciPy stack. It offers various plotting functions such as line, bar, scatter, and histogram, and can be utilized in scripts, shells, and web applications. The library includes a Pyplot module that provides a MATLAB-like interface for easy plotting and customization of visualizations.

Uploaded by

Vidya Jayakumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Data Visualization

Matplotlib
• Matplotlib is an amazing visualization library in Python for 2D plots
of arrays. Matplotlib is a multi-platform data visualization library built
on NumPy arrays and designed to work with the broader SciPy stack.
It was introduced by John Hunter in the year 2002.
• One of the greatest benefits of visualization is that it allows us visual
access to huge amounts of data in easily digestible visuals. Matplotlib
consists of several plots like line, bar, scatter, histogram etc.
Continued…
• Basic plots in Matplotlib :
• Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make
correlations. They’re typically instruments for reasoning about quantitative information. Some of the sample plots
are covered here.
• # importing matplotlib module
• from matplotlib import pyplot as plt

• # x-axis values
• x = [5, 2, 9, 4, 7]

• # Y-axis values
• y = [10, 5, 8, 4, 2]

• # Function to plot
• plt.plot(x,y)

• # function to show the plot


• plt.show()
Continued…
• # importing matplotlib module
• from matplotlib import pyplot as plt

• # x-axis values
• x = [5, 2, 9, 4, 7]

• # Y-axis values
• y = [10, 5, 8, 4, 2]

• # Function to plot the bar


• plt.bar(x,y)

• # function to show the plot


• plt.show()
Continued…
• # importing matplotlib module
• from matplotlib import pyplot as plt

• # Y-axis values
• y = [10, 5, 8, 4, 2]

• # Function to plot histogram


• plt.hist(y)

• # Function to show the plot


• plt.show()
Continued…

• # importing matplotlib module


• from matplotlib import pyplot as plt

• # x-axis values
• x = [5, 2, 9, 4, 7]

• # Y-axis values
• y = [10, 5, 8, 4, 2]

• # Function to plot scatter


• plt.scatter(x, y)

• # function to show the plot


• plt.show()
Pyplot in Matplotlib
• Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in
Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like
Tkinter, awxPython, etc.

• Note: For more information, refer to Python Matplotlib – An Overview

• Installation
• To use Pyplot we must first download matplotlib module. The best way to do this is –

• pip install matplotlib


• Pyplot
• Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB,
with the ability to use Python and the advantage of being free and open-source. Each pyplot function makes some change to a
figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with
labels, etc. The various plots we can utilize using Pyplot are Line Plot, Histogram, Scatter, 3D Plot, Image, Contour, and
Polar.

• Syntax :

• matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)


Continue…
• # Python program to show plot function

• import matplotlib.pyplot as plt

• plt.plot([1, 2, 3, 4], [1, 4, 9, 16])


• plt.axis([0, 6, 0, 20])
• plt.show()
Continued…
• The plot function marks the x-coordinates(1, 2, 3, 4) and y-coordinates(1, 4, 9, 16)
in a linear graph with specified scales. [/caption]
• Parameters: This function accepts parameters that enables us to set axes scales and
format the graphs. These parameters are mentioned below :-
• plot(x, y): plot x and y using default line style and color.
• plot.axis([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from minimum
to maximum values
• plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2,
markersize=12): x and y co-ordinates are marked using circular markers of size 12
and green color line with — style of width 2
• plot.xlabel(‘X-axis’): names x-axis
• plot.ylabel(‘Y-axis’): names y-axis
• plot(x, y, label = ‘Sample line ‘) plotted Sample Line will be displayed as a legend
Continued…
• # Python Program to illustrate Linear Plotting
• import matplotlib.pyplot as plt
• # year contains the x-axis values
• # and e-india & e-bangladesh
• # are the y-axis values for plotting
• year = [1972, 1982, 1992, 2002, 2012]
• e_india = [100.6, 158.61, 305.54, 394.96, 724.79]
• e_bangladesh = [10.5, 25.21, 58.65, 119.27, 274.87]
• # plotting of x-axis(year) and
• # y-axis(power consumption)
• with different colored labels of two countries
• plt.plot(year, e_india, color ='orange',
• label ='India')

• plt.plot(year, e_bangladesh, color ='g',


• label ='Bangladesh')
• # naming of x-axis and y-axis
• plt.xlabel('Years')
• plt.ylabel('Power consumption in kWh')
• # naming the title of the plot
• plt.title('Electricity consumption per capita\
• of India and Bangladesh')

• plt.legend()
• plt.show()
Continued…
• # Python Program to illustrate Linear Plotting • plt.plot(year, e_bangladesh, color ='g',
• linestyle ='dashed', linewidth = 2,label ='Bangladesh')

• import matplotlib.pyplot as plt


• plt.xlabel('Years')
• year = [1972, 1982, 1992, 2002, 2012] • plt.ylabel('Power consumption in kWh')
• e_india = [100.6, 158.61, 305.54,
• 394.96, 724.79] • plt.title('Electricity consumption per \
• capita of India and Bangladesh')
• e_bangladesh = [10.5, 25.21, 58.65,
• plt.legend()
• 119.27,
274.87] • plt.show()

• # formatting of line style and


• # plotting of co-ordinates
• plt.plot(year, e_india, color ='orange',
• marker ='o', markersize = 12,
• label ='India')
Matplotlib – Axes Class
• Matplotlib is one of the Python packages which is used for data visualization. You can use the NumPy
library to convert data into an array and numerical mathematics extension of Python. Matplotlib library is
used for making 2D plots from data in arrays.

• Axes class
• Axes is the most basic and flexible unit for creating sub-plots. Axes allow placement of plots at any
location in the figure. A given figure can contain many axes, but a given axes object can only be in one
figure. The axes contain two axis objects 2D as well as, three-axis objects in the case of 3D. Let’s look at
some basic functions of this class.

• axes() function
• axes() function creates axes object with argument, where argument is a list of 4 elements [left, bottom,
width, height]. Let us now take a brief look to understand the axes() function.

• Syntax :

• axes([left, bottom, width, height])


Continued…

• import matplotlib.pyplot as plt


• fig = plt.figure()
• #[left, bottom, width, height]
• ax = plt.axes([0.1, 0.1, 0.8, 0.8])

• Here in axes([0.1, 0.1, 0.8, 0.8]), the first ‘0.1’ refers to the distance
between the left side axis and border of the figure window is 10%, of
the total width of the figure window. The second ‘0.1’ refers to the
distance between the bottom side axis and the border of the figure
window is 10%, of the total height of the figure window. The first ‘0.8’
means the axes width from left to right is 80% and the latter ‘0.8’
means the axes height from the bottom to the top is 80%
Continued..
• add_axes() function
• Alternatively, you can also add the axes object to the figure by calling
the add_axes() method. It returns the axes object and adds axes at
position [left, bottom, width, height] where all quantities are in
fractions of figure width and height.
• Syntax :

• add_axes([left, bottom, width, height])


Continued…
• import matplotlib.pyplot as plt

• fig = plt.figure()

• #[left, bottom, width, height]


• ax = fig.add_axes([0, 0, 1, 1])
Continued…
• ax.legend() function
• Adding legend to the plot figure can be done by calling the legend()
function of the axes class. It consists of three arguments.

• Syntax :

• ax.legend(handles, labels, loc)


• Where labels refers to a sequence of string and handles, a sequence of
Line2D or Patch instances, loc can be a string or an integer specifying the
location of legend.
Continued…

• import matplotlib.pyplot as plt

• fig = plt.figure()

• #[left, bottom, width, height]


• ax = plt.axes([0.1, 0.1, 0.8, 0.8])

• ax.legend(labels = ('label1', 'label2'),


• loc = 'upper left')
Continued…
• ax.plot() function
• plot() function of the axes class plots the values of one array versus another as line or marker.

• Syntax : plt.plot(X, Y, ‘CLM’)

• Parameters:
• X is x-axis.
• Y is y-axis.
• ‘CLM’ stands for Color, Line and Marker.

• Note: Line can be of different styles such as dotted line (':'), dashed line ('—'), solid line ('-') and
many more.
Continued…
• Marker codes

• Characters Description
• ‘.’ Point Marker
• ‘o’ Circle Marker
• ‘+’ Plus Marker
• ‘s’ Square Marker
• ‘D’ Diamond Marker
• ‘H’ Hexagon Marker
Continued…
• import matplotlib.pyplot as plt •#'ro-' mentions red color, circle​
• import numpy as np •# marker with solid line.​
•ax2 = ax.plot(X, S, 'ro-')​
•​
• X = np.linspace(-np.pi, np.pi, 15) •ax.legend(labels = ('Cosine Function',​
• C = np.cos(X) •'Sine Function'),​
• S = np.sin(X) •loc = 'upper left')​
•​
• # [left, bottom, width, height] •ax.set_title("Trigonometric Functions")​
• ax = plt.axes([0.1, 0.1, 0.8, 0.8]) •​
•plt.show()​
• # 'bs:' mentions blue color, square
• # marker with dotted line.
• ax1 = ax.plot(X, C, 'bs:')
Subplot

• To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along
with Axes object or array of Axes object. nrows, ncols attributes of subplots() method
determine the number of rows and columns of the subplot grid.

• By default, it returns a figure with a single plot. For each axes object i.e plot we can set title
(set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).

• Let’s see how this works

• When we call the subplots() method by stacking only in one direction it returns a 1D array of
axes object i.e subplots.
• We can access these axes objects using indices just like we access elements of the array. To
create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes.
Refer to the following figure for a better understanding
Continued…
• # importing library
• import matplotlib.pyplot as plt

• # Some data to display


• x = [1, 2, 3]
• y = [0, 1, 0]
• z = [1, 0, 1]

• # Creating 2 subplots
• fig, ax = plt.subplots(2)

• # Accessing each axes object to plot the data through returned array
• ax[0].plot(x, y)
• ax[1].plot(x, z)
Continued…

• # importing library
• import matplotlib.pyplot as plt
• import numpy as np

• # Data for plotting


• x = np.arange(0.0, 2.0, 0.01)
• y = 1 + np.sin(2 * np.pi * x)

• # Creating 6 subplots and unpacking the output array immediately


• fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)
• ax1.plot(x, y, color="orange")
• ax2.plot(x, y, color="green")
• ax3.plot(x, y, color="blue")
• ax4.plot(x, y, color="magenta")
• ax5.plot(x, y, color="black")
• ax6.plot(x, y, color="red")
Add Title to Subplots in Matplotlib

• Steps Needed
• Import Libraries
• Create/ Load data
• Make subplot
• Plot subplot
• Set title to subplots.
Example 1: (Using set_title() method)

We use matplotlib.axes._axes.Axes.set_title(label) method to set title (string label) for the current
subplot Axes.
• # set data with subplots and plot
• # importing packages • ax[0, 0].plot(x, x)
• import numpy as np • ax[0, 1].plot(x, x*2)
• ax[1, 0].plot(x, x*x)
• import • ax[1, 1].plot(x, x*x*x)
matplotlib.pyplot as plt
• # set the title to subplots
• # create data • ax[0, 0].set_title("Linear")
• ax[0, 1].set_title("Double")
• x=np.array([1, 2, 3, 4, • ax[1, 0].set_title("Square")
5]) • ax[1, 1].set_title("Cube")

• # making subplots • # set spacing


• fig, ax = plt.subplots(2, • fig.tight_layout()
• plt.show()
2)
Example 2: (Using title.set_text() method)

We can also add title to subplots in Matplotlib using title.set_text() method, in similar way to
set_title() method.
• # set data with subplots and plot
• # importing packages
• ax[0, 0].plot(x, x)
• import numpy as np • ax[0, 1].plot(x, x*2)
• ax[1, 0].plot(x, x*x)
• import matplotlib.pyplot as • ax[1, 1].plot(x, x*x*x)
plt
• # set the title to subplots
• ax[0, 0].title.set_text("Linear")
• # create data • ax[0, 1].title.set_text("Double")
• x=np.array([1, 2, 3, 4, 5]) • ax[1, 0].title.set_text("Square")
• ax[1, 1].title.set_text("Cube")

• # set spacing
• # making subplots
• fig.tight_layout()
• fig, ax = plt.subplots(2, 2) • plt.show()
Thank You

You might also like