MATPLOTLIB
Matplotlib
• Matplotlib is a low level graph plotting library in python that
serves as a visualization utility.
• Matplotlib was created by John D. Hunter.
• Matplotlib is open source and we can use it freely.
• Matplotlib is mostly written in python, a few segments are
written in C, Objective-C and Javascript for Platform
compatibility.
Matplotlib Pyplot
• Most of the Matplotlib utilities lies under
the pyplot submodule, and are usually imported under
the plt alias:
import matplotlib.pyplot as plt
Matplotlib Plotting
• Plotting x and y points
• The plot() function is used to draw points (markers) in a
diagram.
• By default, the plot() function draws a line from point to point.
• The function takes parameters for specifying points in the
diagram.
• Parameter 1 is an array containing the points on the x-axis.
• Parameter 2 is an array containing the points on the y-axis.
• If we need to plot a line from (1, 3) to (8, 10), we have to pass
two arrays [1, 8] and [3, 10] to the plot function.
Draw a line in a diagram from position (1, 3) to position (8, 10):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints)
plt.show()
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
Draw two points in the diagram, one at position (1, 3) and one
in position (8, 10):
• import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6,
1) and finally to position (8, 10):
• import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()
Plotting without x-points:
• import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()
• The x-points in the example above is [0, 1, 2, 3, 4, 5].
Mark each point with a circle:
• import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o')
plt.show()
Color Reference
Color Syntax Description
'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
Line Reference
Line Syntax Description
'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line
Matplotlib Line
• Linestyle
use the keyword argument linestyle, or shorter ls, to change the style of
the plotted line:
• Use a dotted line:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()
Use a dashed line:
plt.plot(ypoints, linestyle = 'dashed')
Shorter Syntax
• The line style can be written in a shorter syntax:
• linestyle can be written as ls.
• dotted can be written as :.
• dashed can be written as --.
•
Shorter syntax:
plt.plot(ypoints, ls = ':')
Line Color
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, color = 'r')
plt.show()
Line Width
• import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linewidth = '20.5')
plt.show()
Matplotlib Labels and Title
• Create Labels for a Plot
•
use the xlabel() and ylabel() functions to set a label for the x-
and y-axis.
Legends
• A legend is an area describing the elements of the graph. In
the matplotlib library, there’s a function called legend() which
is used to Place a legend on the axes.
• The attribute Loc in legend() is used to specify the location of
the legend.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.It’s default value is 1.
Syntax
• plt.legend()
• Example
• plt.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15),
ncol=2)
Attributes
• The Following are some more attributes of function legend() :
• shadow: [None or bool] Whether to draw a shadow behind the
legend.It’s Default value is None.
• markerscale: [None or int or float] The relative size of legend
markers compared with the originally drawn ones.The Default is
None.
• numpoints: [None or int] The number of marker points in the legend
when creating a legend entry for a Line2D (line).The Default is None.
• fontsize: The font size of the legend.If the value is numeric the size
will be the absolute font size in points.
• facecolor: [None or “inherit” or color] The legend’s background
color.
• edgecolor: [None or “inherit” or color] The legend’s background
patch edge color.
Single legends
import numpy as np
import matplotlib.pyplot as plt
# X-axis values
x = [1, 2, 3, 4, 5]
# Y-axis values
y = [1, 4, 9, 16, 25]
# Function to plot
plt.plot(x, y)
# Function add a legend
plt.legend(['single element'])
# function to show the plot
plt.show()
Multiple legends
# importing modules
import numpy as np
import matplotlib.pyplot as plt
# Y-axis values
y1 = [2, 3, 4.5]
# Y-axis values
y2 = [1, 1.5, 5]
# Function to plot
plt.plot(y1)
plt.plot(y2)
# Function add a legend
plt.legend(["blue", "green"], loc ="lower right")
# function to show the plot
plt.show()
Add labels to the x- and y-axis:
• import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Create a Title for a Plot
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
Matplotlib Adding Grid Lines
• import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.grid()
plt.show()
Display Multiple Plots
• With the subplot() function you can draw multiple plots in one figure:
• import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
• The subplot() function takes three arguments that describes
the layout of the figure.
• The layout is organized in rows and columns, which are
represented by the first and second argument.
• The third argument represents the index of the current plot.
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is
the first plot.
plt.subplot(1, 2, 2)
the figure has 1 row, 2 columns, and this plot is
the second plot.
Matplotlib Scatter
• With Pyplot, you can use the scatter() function to draw a scatter
plot.
• The scatter() function plots one dot for each observation. It needs
two arrays of the same length, one for the values of the x-axis, and
one for values on the y-axis
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
Draw two plots on the same
figure:
• import matplotlib.pyplot as plt
import numpy as np
#day one, the age and speed of 13 cars:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
#day two, the age and speed of 15 cars:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y=
np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)
plt.show()
Set your own color of the
markers:
• import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y=
np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85
])
plt.scatter(x, y, color = '#88c999')
plt.show()
Matplotlib Bars
• With Pyplot, you can use the bar() function to draw bar
graphs:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
Bar chart
Horizontal Bars
• import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y)
plt.show()
Bar Color
• import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, color = "red")
plt.show()
Bar Width
• import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, width = 0.1)
plt.show()
Bar Height
• The barh() takes the keyword argument height to set the height of the
bars:
• The Matplotlib barh() function plots horizontal bar graphs in Python.
• Using the Numpy arrange function creating two arrays. The array ‘x’
contains the name of the four horizontal bars.
• And the array ‘y’ contains the sequence of y coordinates of the bar. The
‘x’ and ‘y’ are arguments to the matplotlib barh() function to get the
desired horizontal bar plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y, height = 0.1)
plt.show()
Matplotlib Histograms
• Histogram
• A histogram is a graph showing frequency distributions.
• It is a graph showing the number of observations within each
given interval.
• Example: Say you ask for the height of 250 people, you might
end up with a histogram like this:
Create Histogram
• In Matplotlib, we use the hist() function to create histograms.
• The hist() function will use an array of numbers to create a
histogram, the array is sent into the function as an argument.
• For simplicity we use NumPy to randomly generate an array
with 250 values, where the values will concentrate around 170,
and the standard deviation is 10.
import numpy as np
x = np.random.normal(170, 10, 250)
print(x)
plt.hist(x)
plt.show()
Pie Chart
• With Pyplot, you can use the pie() function to draw pie charts:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
plt.pie(y)
plt.show()
Labels
• Labels
• Add labels to the pie chart with the label parameter.
• The label parameter must be an array with one label for each
wedge:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels = mylabels)
plt.show()