Tutorial Matplotlib
Tutorial Matplotlib
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 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.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.
Install it using this command:
C:\Users\Your Name>pip install matplotlib
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
Now Matplotlib is imported and ready to use:
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Example 2:
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Hasil:
Matplotlib Plotting
1. 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.
Example
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()
Result:
The x-axis is the horizontal axis dan the y-axis is the vertical axis.
2. Plotting Without Line
To plot only the markers, you can use shortcut string notation parameter 'o', which
means 'rings'.
Example:
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
Result:
3. 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):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Result:
4. 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:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints)
plt.show()
Result:
The x-points in the example above is [0, 1, 2, 3, 4, 5].
Matplotlib Markers
1. Markers
You can use the keyword argument marker to emphasize each point with a
specified marker.
Example
Mark each point with a circle:
import matplotlib.pyplot as plt
import numpy as np
Result:
The marker value can be anything from the Marker Reference above.
The line value can be one of the following:
Line Reference
Line Syntax Description
'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line
Note: If you leave out the line value in the fmt parameter, no line will be plottet.
The short color value can be one of the following:
Color Reference
3. 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:
import matplotlib.pyplot as plt
import numpy as np
Result:
4. 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:
import matplotlib.pyplot as plt
import numpy as np
Result:
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:
import matplotlib.pyplot as plt
import numpy as np
Result:
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 --.
Example
Shorter syntax:
plt.plot(ypoints, ls = ':')
Result:
Line Styles
You can choose any of these styles:
Style Or
'dotted' ':'
'dashed' '--'
'dashdot' '-.'
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:
import matplotlib.pyplot as plt
import numpy as np
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:
import matplotlib.pyplot as plt
import numpy as np
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])
plt.plot(y1)
plt.plot(y2)
plt.show()
Result:
Try it Yourself »
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).)
The x- and y- values come in pairs:
Example
Draw two lines by specifiyng the x- and y-point values for both lines:
import matplotlib.pyplot as plt
import numpy as np
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])
❮ PreviousNext ❯
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:
Try it Yourself »
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:
Try it Yourself »
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}
Try it Yourself »
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:
Try it Yourself »
❮ PreviousNext ❯
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.grid()
plt.show()
Result:
Try it Yourself »
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:
Try it Yourself »
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:
Try it Yourself »
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(color = 'green', linestyle = '--', linewidth = 0.5)
plt.show()
Result:
Try it Yourself »
Matplotlib Subplots
❮ PreviousNext ❯
#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:
Try it Yourself »
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:
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(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:
Try it Yourself »
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:
import matplotlib.pyplot as plt
import numpy as np
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:
Try it Yourself »
Title
You can add a title to each plot with the title() function:
Example
2 plots, with titles:
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)
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:
Try it Yourself »
Super Title
You can add a title to the entire figure with the suptitle() function:
Example
Add a title for the entire 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)
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:
Matplotlib Scatter
❮ PreviousNext ❯
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:
Try it Yourself »
The observation in the example above is the result of 13 cars passing by.
The X-axis shows how old the car is.
The Y-axis shows the speed of the car when it passes.
Are there any relationships between the observations?
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:
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)
plt.show()
Result:
Try it Yourself »
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 = p.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:
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","b
rown","gray","cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
Result:
Try it Yourself »
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.
Here is an example of a colormap:
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.
How to Use the ColorMap
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:
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])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.show()
Result:
Try it Yourself »
You can include the colormap in the drawing by including
the plt.colorbar() statement:
Example
Include the actual colormap:
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])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.colorbar()
plt.show()
Result:
Try it Yourself »
Available ColorMaps
You can choose any of the built-in colormaps:
Name Reverse
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:
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])
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:
Try it Yourself »
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:
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])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
Try it Yourself »
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:
Try it Yourself »
Matplotlib Bars
❮ PreviousNext ❯
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
Example
Draw 4 bars:
import matplotlib.pyplot as plt
import numpy as np
plt.bar(x,y)
plt.show()
Result:
Try it Yourself »
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)
Try it Yourself »
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use
the barh() function:
Example
Draw 4 horizontal bars:
import matplotlib.pyplot as plt
import numpy as np
Try it Yourself »
Bar Color
The bar() and barh() takes the keyword argument color to set the color of the bars:
Example
Draw 4 red bars:
import matplotlib.pyplot as plt
import numpy as np
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
Example
Draw 4 very thin bars:
import matplotlib.pyplot as plt
import numpy as np
Bar Height
The barh() takes the keyword argument height to set the height of the bars:
Example
Draw 4 very thin bars:
import matplotlib.pyplot as plt
import numpy as np
❮ PreviousNext ❯
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:
You can read from the histogram that there are approximately:
2 people from 140 to 145cm
5 people from 145 to 150cm
15 people from 151 to 156cm
31 people from 157 to 162cm
46 people from 163 to 168cm
53 people from 168 to 173cm
45 people from 173 to 178cm
28 people from 179 to 184cm
21 people from 185 to 190cm
4 people from 190 to 195cm
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:
Try it Yourself »
The hist() function will read the array and produce a histogram:
Example
A simple histogram:
import matplotlib.pyplot as plt
import numpy as np
plt.hist(x)
plt.show()
Result:
Try it Yourself »
❮ PreviousNext ❯
plt.pie(y)
plt.show()
Result:
Try it Yourself »
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:
The value divided by the sum of all values: x/sum(x)
ADVERTISEMENT
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:
import matplotlib.pyplot as plt
import numpy as np
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.
The startangle parameter is defined with an angle in degrees, default angle is 0:
Example
Start the first wedge at 90 degrees:
import matplotlib.pyplot as plt
import numpy as np
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:
import matplotlib.pyplot as plt
import numpy as np
Shadow
Add a shadow to the pie chart by setting the shadows parameter to True:
Example
Add a shadow:
import matplotlib.pyplot as plt
import numpy as np
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:
import matplotlib.pyplot as plt
import numpy as np
Legend
To add a list of explanation for each wedge, use the legend() function:
Example
Add a legend:
import matplotlib.pyplot as plt
import numpy as np
Try it Yourself »
Legend With Header
To add a header to the legend, add the title parameter to the legend function.
Example
Add a legend with a header:
import matplotlib.pyplot as plt
import numpy as np