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

Matplotlib_Functions

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

Python Programming

UNIT – IV

Topic : matplotlib

Mrs. M. Rajya Lakshmi


Assoc. Professor
Department of IT
Introduction to matplotlib:

• Matplotlib is one of the most popular Python packages used for data
visualization.
• Data visualization can perform below tasks:
• It identifies areas that need improvement and attention.
• It clarifies the factors.
• It helps to understand which product to place where.
• Predict sales volumes.
Working of matplotlib: Matplotlib Architecture
• There are three different layers in the architecture of the matplotlib
which are the following:
• Backend Layer : The backend layer is the bottom layer of the figure,
which consists of the implementation of the various functions that are
necessary for plotting. There are three essential classes from the
backend layer FigureCanvas(The surface on which the figure will be
drawn), Renderer(The class that takes care of the drawing on the
surface), and Event(It handle the mouse and keyboard events).
• Artist layer : The artist layer is the second layer in the architecture. It is
responsible for the various plotting functions, like axis, which
coordinates on how to use the renderer on the figure canvas.
• Scripting layer : The scripting layer is the topmost layer on which most
of our code will run. The methods in the scripting layer, almost
automatically take care of the other layers, and all we need to care about
is the current state (figure & subplot).
Introduction to matplotlib:
• A Matplotlib figure can be categorized into various parts as below:

• Figure: It is a whole figure which may hold one or more axes (plots).

• Axes: A Figure can contain several Axes. It consists of two or three


(in the case of 3D) Axis objects. Each Axes is comprised of a title, an
x-label, and a y-label.

• Axis: Axises are the number of line like objects and responsible for
generating the graph limits.

• Artist: An artist is the all which we see on the graph like Text
objects, Line2D objects, and collection objects.
Introduction to matplotlib:
Important functions of matplotlib:
Important functions of matplotlib:
Important functions of matplotlib:
Types of Plots:

• There are various plots which can be created using python matplotlib.
• Some of them are listed below:
Types of Plots : Line Plot

• The line graph is one of charts which shows information as a series of


the line. The graph is plotted by the plot() function. The line graph is
simple to plot;

from matplotlib import pyplot as plt


plt.plot([1,2,3],[4,5,1])
plt.show()
Modifying the appearance of Plots: The matplotlib supports the
following color abbreviations.
Line Graph: Example

from matplotlib import pyplot as plt


plt.plot([1,2,3],[4,5,1],’^k’)
plt.show()
Line Plot: Example

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x),'r')
Bar Plot:
• Bar graphs are one of the most common types of graphs and are used to
show data associated with the categorical variables.
• Matplotlib provides a bar() to make bar graphs which accepts arguments
such as: categorical variables, their value and color.

from matplotlib import pyplot as plt


players = ['Virat','Rohit','Shikhar','Hardik’]
runs = [51,87,45,67]
plt.bar(players,runs,color = 'green’)
plt.title('Score Card’)
plt.xlabel('Players’)
plt.ylabel('Runs’)
plt.show()
Bar Plot:
• Another function barh() is used to make horizontal bar graphs. It
accepts xerr or yerr as arguments

from matplotlib import pyplot as plt


players = ['Virat','Rohit','Shikhar','Hardik’]
runs = [51,87,45,67]
plt.barh(players,runs, color = 'green’)
plt.title('Score Card’)
plt.xlabel('Players’)
plt.ylabel('Runs’)
plt.show()
Bar Plot: Example
from matplotlib import pyplot as plt
x1 = [5,8,11] y1 = [12,16,6]
x2 = [6,9,12] y2 = [7,15,7]
plt.bar(x1, y1, color = 'y', label='2019',align='center’)
plt.bar(x2, y2, color='c', label='2020',align='center’)
plt.title('Profits/Loss Information’)
plt.legend(loc="upper right")
plt.ylabel('Sales in Crores’)
plt.xlabel('Categories')
Bar Plot: Example
from matplotlib import pyplot as plt
import numpy as np
countries = ['USA', 'India', 'China', 'Russia', 'Germany’]
bronzes = np.array([38, 17, 26, 19, 15])
silvers = np.array([37, 23, 18, 18, 10])
golds = np.array([46, 27, 26, 19, 17])
ind = [x for x,y in enumerate(countries)]
plt.bar(ind, golds, width=0.5, label='golds', color='gold',
bottom=silvers+bronzes)
plt.bar(ind, silvers, width=0.5, label='silvers', color='silver', bottom=bronzes)
plt.bar(ind, bronzes, width=0.5, label='bronzes', color='#CD853F')
plt.xticks(ind, countries)
plt.ylabel("Medals")
plt.xlabel("Countries")
plt.legend(loc="upper right")
plt.title("2019 Olympics Top Medal Winners")
Bar Plot:Example
Pie Chart:

• A pie chart is a circular graph that is broken down in the segment or


slices of pie.
• It is generally used to represent the percentage or proportional data
where each slice of pie represents a particular category
Pie Chart:Example

from matplotlib import pyplot as plt


Players = [‘Rohit’, ‘Virat’, ‘Shikhar’, ‘Yuvraj’]
Runs = [45, 30, 15, 10]
e = (0.1, 0, 0, 0) # it "explode" the 1st slice
plt.pie(Runs,explode=e,labels=Players,
autopct='%1.1f%%’,
shadow=True,startangle=90)
plt.show()
Histogram:

• A histogram is used for the distribution, whereas a bar chart is used to


compare different entities.
• A histogram is a type of bar plot that shows the frequency of a number of
values compared to a set of values ranges.
• For example we take the data of the different age group of the people and
plot a histogram with respect to the bin.
• Now, bin represents the range of values that are divided into series of
intervals. Bins are generally created of the same size.
Histogram:
from matplotlib import pyplot as plt
age=[21,53,60,49,25,27,30,42,40,1,2,102,95,8,15,105,70,65,55,70,75,60,5
2,44,43,42,45]
bins = [0,20,40,60,80,100]
plt.hist(age, bins, histtype='bar', rwidth=0.8) #step,stepfilled,bar
plt.xlabel('age groups’)
plt.ylabel('Number of people’)
plt.title('Histogram’)
plt.show()
Scatter Plot:

• The scatter plots are mostly used for comparing variables when we need
to define how much one variable is affected by another variable.
• The data is displayed as a collection of points.
• Each point has the value of one variable, which defines the position on
the horizontal axes, and the value of other variable represents the
position on the vertical axis.
Scatter Plot:
import matplotlib.pyplot as plt
x = [2, 2.5, 3, 3.5, 4.5, 4.7, 5.0]
y = [7.5, 8, 8.5, 9, 9.5, 10, 10.5]
x1 = [9, 8.5, 9, 9.5, 10, 10.5, 12]
y1 = [3, 3.5, 4.7, 4, 4.5, 5, 5.2]
plt.scatter(x, y,
label='high income low saving’, color='g’)
plt.scatter(x1, y1,
label='low income high savings', color='r’)
plt.xlabel('saving*100’)
plt.ylabel('income*1000’)
plt.title('Scatter Plot’)
plt.legend()
plt.show()
Area Plot:

• Area plots are pretty much similar to the line plot.


• They are also known as stack plots.
• These plots can be used to track changes over time for two or more
related groups that make up one whole category.
• For example, let’s compile the work done during a day into categories, say
sleeping, eating, working and playing.
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
plt.plot([],[],color='m', label='Sleeping', linewidth=5)
plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='k', label='Playing', linewidth=5)
plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k’])
plt.xlabel(‘x’) plt.ylabel(‘y’) plt.title('Stack Plot’)
plt.legend()
plt.show()
Area Plot:
Plotting multiple Plots(Subplots):

• Subplots are required when we want to show two or more plots in same
figure.
• The Matplotlib subplot() function is defined as to plot two or more plots in
one figure.
• We can use this method to separate two graphs which plotted in the same
axis Matplotlib supports all kinds of subplots, including 2x1 vertical, 2x1
horizontal, or a 2x2 grid.
• It accepts the three arguments: they are nrows, ncols, and index.
• It denote the number of rows, number of columns and the index.
Subplots:Example
from matplotlib import pyplot as plt
names = ['Abhishek', 'Himanshu', 'Devansh’]
marks= [87,50,98]
plt.figure(figsize=(9,3))
plt.subplot(131)
plt.bar(names, marks)
plt.subplot(132)
plt.scatter(names, marks)
plt.subplot(133)
plt.plot(names, marks)
plt.suptitle('Categorical Plotting’)
plt.show()
Subplots:Example2
import matplotlib.pyplot as plt
import numpy as np
def create_plot(ptype):
x = np.arange(-10, 10, 0.01) # x-axis
if ptype == 'linear’:
y=x
elif ptype == 'quadratic’:
y = x**2
elif ptype == 'cubic’:
y = x**3
elif ptype == 'quartic’:
y = x**4
return(x, y)
Subplots:Example2
fig = plt.figure()
plt1 = fig.add_subplot(221)
plt2 = fig.add_subplot(222)
plt3 = fig.add_subplot(223)
plt4 = fig.add_subplot(224)
x, y = create_plot('linear') plt1.plot(x, y, color ='r') plt1.set_title('y1=x’)
x, y = create_plot('quadratic') plt2.plot(x, y, color ='b') plt2.set_title('y2 = x2’)
x, y = create_plot('cubic') plt3.plot(x, y, color ='g') plt3.set_title('y3 = x3’)
x, y = create_plot('quartic') plt4.plot(x, y, color ='k') plt4.set_title('y4 = x4’)
# adjusting space between subplots
fig.subplots_adjust(hspace=.5,wspace=0.5)
plt.show()
Subplots:

You might also like