Unit 5
Unit 5
❮ PreviousNext ❯
What is 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 mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform
compatibility.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy.
If this command fails, then use a python distribution that already has Matplotlib installed, like Anaconda, Spyder
etc.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module statement:
import matplotlib
Example
import matplotlib
print(matplotlib.__version__)
Matplotlib Pyplot
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:
Example
Draw a line in a diagram from position (0,0) to position (6,250):
plt.plot(xpoints, ypoints)
plt.show()
Result:
Matplotlib Plotting
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.
Example
Draw a line in a diagram from position (1, 3) to position (8, 10):
plt.plot(xpoints, ypoints)
plt.show()
Result:
Result:
Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in both axis.
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10):
plt.plot(xpoints, ypoints)
plt.show()
Result:
Default X-Points
If we do not specify the points in the x-axis, they will get the default values 0, 1, 2, 3, (etc. depending on the length
of the y-points.
So, if we take the same example as above, and leave out the x-points, the diagram will look like this:
Example
Plotting without x-points:
plt.plot(ypoints)
plt.show()
Result:
Matplotlib Markers
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
Example
Mark each point with a circle:
Example
Mark each point with a star:
...
plt.plot(ypoints, marker = '*')
...
Result:
Marker Reference
You can choose any of these markers:
Marker Description
'o' Circle Try it »
'x' X Try it »
This parameter is also called fmt, and is written with this syntax:
marker|line|color
Example
Mark each point with a circle:
plt.plot(ypoints, 'o:r')
plt.show()
Result:
The marker value can be anything from the Marker Reference above.
Line Reference
Line Syntax Description
Note: If you leave out the line value in the fmt parameter, no line will be plottet.
Color Reference
Color Syntax Description
'r' Red Try it »
Marker Size
You can use the keyword argument markersize or the shorter version, ms to set the size of the markers:
Example
Set the size of the markers to 20:
Marker Color
You can use the keyword argument markeredgecolor or the shorter mec to set the color of the edge of the
markers:
Example
Set the EDGE color to red:
You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge of the
markers:
Example
Set the FACE color to red:
Use both the mec and mfc arguments to color of the entire marker:
Example
Set the color of both the edge and the face to red:
Result:
...
plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc = '#4CAF50')
...
Result:
Example
Mark each point with the color named "hotpink":
...
plt.plot(ypoints, marker = 'o', ms = 20, mec = 'hotpink', mfc = 'hotpink')
...
Result:
AliceBlue
#F0F8FF
AntiqueWhite
#FAEBD7
Aqua
#00FFFF
Aquamarine
#7FFFD4
Azure
#F0FFFF
Beige
#F5F5DC
Bisque
#FFE4C4
Black
#000000
BlanchedAlmond
#FFEBCD
Blue
#0000FF
BlueViolet
#8A2BE2
Brown
#A52A2A
BurlyWood
#DEB887
CadetBlue
#5F9EA0
Chartreuse
#7FFF00
Chocolate
#D2691E
Coral
#FF7F50
CornflowerBlue
#6495ED
Cornsilk
#FFF8DC
Crimson
#DC143C
Cyan
#00FFFF
DarkBlue
#00008B
DarkCyan
#008B8B
DarkGoldenRod
#B8860B
DarkGray
#A9A9A9
DarkGrey
#A9A9A9
DarkGreen
#006400
DarkKhaki
#BDB76B
DarkMagenta
#8B008B
DarkOliveGreen
#556B2F
DarkOrange
#FF8C00
DarkOrchid
#9932CC
DarkRed
#8B0000
DarkSalmon
#E9967A
DarkSeaGreen
#8FBC8F
DarkSlateBlue
#483D8B
DarkSlateGray
#2F4F4F
DarkSlateGrey
#2F4F4F
DarkTurquoise
#00CED1
DarkViolet
#9400D3
DeepPink
#FF1493
DeepSkyBlue
#00BFFF
DimGray
#696969
DimGrey
#696969
DodgerBlue
#1E90FF
FireBrick
#B22222
FloralWhite
#FFFAF0
ForestGreen
#228B22
Fuchsia
#FF00FF
Gainsboro
#DCDCDC
GhostWhite
#F8F8FF
Gold
#FFD700
GoldenRod
#DAA520
Gray
#808080
Grey
#808080
Green
#008000
GreenYellow
#ADFF2F
HoneyDew
#F0FFF0
HotPink
#FF69B4
IndianRed
#CD5C5C
Indigo
#4B0082
Ivory
#FFFFF0
Khaki
#F0E68C
Lavender
#E6E6FA
LavenderBlush
#FFF0F5
LawnGreen
#7CFC00
LemonChiffon
#FFFACD
LightBlue
#ADD8E6
LightCoral
#F08080
-LightCyan
#E0FFFF
LightGoldenRodYellow
#FAFAD2
LightGray
#D3D3D3
LightGrey
#D3D3D3
LightGreen
#90EE90
LightPink
#FFB6C1
LightSalmon
#FFA07A
LightSeaGreen
#20B2AA
LightSkyBlue
#87CEFA
LightSlateGray
#778899
LightSlateGrey
#778899
LightSteelBlue
#B0C4DE
LightYellow
#FFFFE0
Lime
#00FF00
LimeGreen
#32CD32
Linen
#FAF0E6
Magenta
#FF00FF
Maroon
#800000
MediumAquaMarine
#66CDAA
MediumBlue
#0000CD
MediumOrchid
#BA55D3
MediumPurple
#9370DB
MediumSeaGreen
#3CB371
MediumSlateBlue
#7B68EE
MediumSpringGreen
#00FA9A
MediumTurquoise
#48D1CC
MediumVioletRed
#C71585
MidnightBlue
#191970
MintCream
#F5FFFA
MistyRose
#FFE4E1
Moccasin
#FFE4B5
NavajoWhite
#FFDEAD
Navy
#000080
OldLace
#FDF5E6
Olive
#808000
OliveDrab
#6B8E23
Orange
#FFA500
OrangeRed
#FF4500
Orchid
#DA70D6
PaleGoldenRod
#EEE8AA
PaleGreen
#98FB98
PaleTurquoise
#AFEEEE
PaleVioletRed
#DB7093
PapayaWhip
#FFEFD5
PeachPuff
#FFDAB9
Peru
#CD853F
Pink
#FFC0CB
Plum
#DDA0DD
PowderBlue
#B0E0E6
Purple
#800080
RebeccaPurple
#663399
Red
#FF0000
RosyBrown
#BC8F8F
RoyalBlue
#4169E1
SaddleBrown
#8B4513
Salmon
#FA8072
SandyBrown
#F4A460
SeaGreen
#2E8B57
SeaShell
#FFF5EE
Sienna
#A0522D
Silver
#C0C0C0
SkyBlue
#87CEEB
SlateBlue
#6A5ACD
SlateGray
#708090
SlateGrey
#708090
Snow
#FFFAFA
SpringGreen
#00FF7F
SteelBlue
#4682B4
Tan
#D2B48C
Teal
#008080
Thistle
#D8BFD8
Tomato
#FF6347
Turquoise
#40E0D0
Violet
#EE82EE
Wheat
#F5DEB3
White
#FFFFFF
WhiteSmoke
#F5F5F5
Yellow
#FFFF00
YellowGreen
#9ACD32
Matplotlib Line
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:
Example
Use a dotted line:
Example
Use a dashed line:
Result:
Shorter Syntax
The line style can be written in a shorter syntax:
Example
Shorter syntax:
plt.plot(ypoints, ls = ':')
Result:
Line Styles
You can choose any of these styles:
Style Or
Line Color
You can use the keyword argument color or the shorter c to set the color of the line:
Example
Set the line color to red:
Result:
Example
Plot with a beautiful green line:
...
plt.plot(ypoints, c = '#4CAF50')
...
Result:
Example
Plot with the color named "hotpink":
...
plt.plot(ypoints, c = 'hotpink')
...
Result:
Line Width
You can use the keyword argument linewidth or the shorter lw to change the width of the line.
Example
Plot with a 20.5pt wide line:
Result:
#New
Multiple Lines
You can plot as many lines as you like by simply adding more plt.plot() functions:
Example
Draw two lines by specifying a plt.plot() function for each line:
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])
plt.plot(y1)
plt.plot(y2)
plt.show()
Result:
You can also plot many lines by adding the points for the x- and y-axis for each line in the
same plt.plot() function.
(In the examples above we only specified the points on the y-axis, meaning that the points on the x-axis got the the
default values (0, 1, 2, 3).)
Example
Draw two lines by specifiyng the x- and y-point values for both lines:
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])
Example
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()
Result:
Example
Add a plot title and labels for 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.show()
Result:
Example
Set font properties for the title and labels:
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])
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
plt.plot(x, y)
plt.show()
Result:
Legal values are: 'left', 'right', and 'center'. Default value is 'center'.
Example
Position the title to the left:
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.show()
Result:
Matplotlib Adding Grid Lines
Example
Add grid lines to the 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.grid()
plt.show()
Result:
Specify Which Grid Lines to Display
You can use the axis parameter in the grid() function to specify which grid lines to display.
Legal values are: 'x', 'y', and 'both'. Default value is 'both'.
Example
Display only grid lines for the x-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.grid(axis = 'x')
plt.show()
Result:
Example
Display only grid lines for the 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.grid(axis = 'y')
plt.show()
Result:
Example
Set the line properties of the grid:
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)
Result:
Matplotlib Subplots
Display Multiple Plots
With the subplots() function you can draw multiple plots in one figure:
Example
Draw 2 plots:
#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()
Result:
The layout is organized in rows and columns, which are represented by the first and second argument.
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.
So, if we want a figure with 2 rows an 1 column (meaning that the two plots will be displayed on top of each other
instead of side-by-side), we can write the syntax like this:
Example
Draw 2 plots on top of each other:
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
Result:
#New
You can draw as many plots you like on one figure, just descibe the number of rows, columns, and the index of the
plot.
Example
Draw 6 plots:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 6)
plt.plot(x,y)
plt.show()
Result:
Title
You can add a title to each plot with the title() function:
Example
2 plots, with titles:
#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)
plt.title("SALES")
#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.title("INCOME")
plt.show()
Result:
#New
Super Title
You can add a title to the entire figure with the suptitle() function:
Example
Add a title for the entire figure:
#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)
plt.title("SALES")
#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.title("INCOME")
plt.suptitle("MY SHOP")
plt.show()
Result:
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:
Example
A simple scatter plot:
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()
Result:
#New
The observation in the example above is the result of 13 cars passing by.
It seems that the newer the car, the faster it drives, but that could be a coincidence, after all we only registered 13
cars.
Compare Plots
In the example above, there seems to be a relationship between speed and age, but what if we plot the
observations from another day as well? Will the scatter plot tell us something else?
Example
Draw two plots on the same figure:
plt.show()
Result:
#New
Note: The two plots are plotted with two different colors, by default blue and orange, you will learn how to change
colors later in this chapter.
By comparing the two plots, I think it is safe to say that they both gives us the same conclusion: the newer the car,
the faster it drives.
Colors
You can set your own color for each scatter plot with the color or the c argument:
Example
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()
Result:
#New
Example
Set your own color of the markers:
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])
colors =
np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","
cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
Result:
#New
ColorMap
The Matplotlib module has a number of available colormaps.
A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.
This colormap is called 'viridis' and as you can see it ranges from 0, which is a purple color, and up to 100, which is
a yellow color.
You can specify the colormap with the keyword argument cmap with the value of the colormap, in this
case 'viridis' which is one of the built-in colormaps available in Matplotlib.
In addition you have to create an array with values (from 0 to 100), one value for each of the point in the scatter
plot:
Example
Create a color array, and specify a colormap in the scatter plot:
plt.show()
Result:
#New
You can include the colormap in the drawing by including the plt.colorbar() statement:
Example
Include the actual colormap:
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])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.colorbar()
plt.show()
Result:
Size
You can change the size of the dots with the s argument.
Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:
Example
Set your own size for the markers:
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])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
plt.scatter(x, y, s=sizes)
plt.show()
Result:
Alpha
You can adjust the transparency of the dots with the alpha argument.
Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:
Example
Set your own size for the markers:
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])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
plt.show()
Result:
Example
Create random arrays with 100 values for x-points, y-points, colors and sizes:
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))
plt.colorbar()
plt.show()
Result:
Matplotlib Bars
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
Example
Draw 4 bars:
plt.bar(x,y)
plt.show()
Result:
#New
The bar() function takes arguments that describes the layout of the bars.
The categories and their values represented by the first and second argument as arrays.
Example
x = ["APPLES", "BANANAS"]
y = [400, 350]
plt.bar(x, y)
#New
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use the barh() function:
Example
Draw 4 horizontal bars:
plt.barh(x, y)
plt.show()
Result:
#New
Bar Color
The bar() and barh() takes the keyword argument color to set the color of the bars:
Example
Draw 4 red bars:
#New
Color Names
Example
Draw 4 "hot pink" bars:
#New
Color Hex
Example
Draw 4 bars with a beautiful green color:
#New
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
Example
Draw 4 very thin bars:
#New
Bar Height
The barh() takes the keyword argument height to set the height of the bars:
Example
Draw 4 very thin bars:
Matplotlib Histograms
❮ PreviousNext ❯
Histogram
A histogram is a graph showing frequency distributions.
Example: Say you ask for the height of 250 people, you might end up with a histogram like this:
You can read from the histogram that there are approximately:
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. Learn more about Normal Data Distribution in our Machine Learning
Tutorial.
Example
A Normal Data Distribution by NumPy:
import numpy as np
print(x)
Result:
This will generate a random result, and could look like this:
#New
The hist() function will read the array and produce a histogram:
Example
A simple histogram:
plt.hist(x)
plt.show()
Result:
Matplotlib Pie Charts
❮ PreviousNext ❯
Example
A simple pie chart:
plt.pie(y)
plt.show()
Result:
#New
As you can see the pie chart draws one piece (called a wedge) for each value in the array (in this case [35, 25, 25,
15]).
By default the plotting of the first wedge starts from the x-axis and move counterclockwise:
Note: The size of each wedge is determined by comparing the value with all the other values, by using this
formula:
Labels
Add labels to the pie chart with the label parameter.
The label parameter must be an array with one label for each wedge:
Example
A simple pie chart:
Result:
#New
Start Angle
As mentioned the default start angle is at the x-axis, but you can change the start angle by specifying
a startangle parameter.
#New
Explode
Maybe you want one of the wedges to stand out? The explode parameter allows you to do that.
The explode parameter, if specified, and not None, must be an array with one value for each wedge.
Each value represents how far from the center each wedge is displayed:
Example
Pull the "Apples" wedge 0.2 from the center of the pie:
Result:
#New
Shadow
Add a shadow to the pie chart by setting the shadows parameter to True:
Example
Add a shadow:
Result:
#New
Colors
You can set the color of each wedge with the colors parameter.
The colors parameter, if specified, must be an array with one value for each wedge:
Example
Specify a new color for each wedge:
Result:
#New
You can use Hexadecimal color values, any of the 140 supported color names, or one of these shortcuts:
'r' - Red
'g' - Green
'b' - Blue
'c' - Cyan
'm' - Magenta
'y' - Yellow
'k' - Black
'w' - White
Legend
To add a list of explanation for each wedge, use the legend() function:
Example
Add a legend:
#New
To add a header to the legend, add the title parameter to the legend function.
Example
Add a legend with a header: