Introduction to Matplotlib for Plotting
Introduction to Matplotlib for Plotting
and press Enter Key to download and install matplotlib. The pip is a package, which
installs the matplotlib python library.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module
statement:
In [1]: import matplotlib
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
Matplotlib Plotting
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
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):
[Link](xpoints, ypoints)
[Link]()
The X-axis is the horizontal axis.
The Y-axis is the vertical axis.
In [15]: # You can directly plot the graph without using the NumPy array.
import [Link] as plt
xpoints =[1, 8]
ypoints =[3, 10]
[Link](xpoints, ypoints)
[Link]()
EXAMPLE: Draw two points in the diagram, one at position (1, 3) and one in position (8,
10):
xpoints = [Link]([1,8])
ypoints = [Link]([3,10])
[Link](xpoints, ypoints, 'o')
[Link]
In jupyter it is not required to use show() function. But in other IDLE it is required to
use show() function to show the graph.
Multiple Points
You can plot as many points as you like, just make sure you have the same number of
points in both axis.
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to
position (8, 10):
xpoints = [Link]([1,2,6,8])
ypoints = [Link]([3,8,1,10])
[Link](xpoints, ypoints)
[Link]()
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:
ypoints = [Link]([3,8,1,10,5,7])
[Link](ypoints)
[Link]()
x = [Link]([1,2,6,8])
y = [Link]([3,8,1,10])
[Link]([0,10,0,12]) # First two is for X-axis and Others are for Y-axis
[Link](x,y)
[Link]()
Matplotlib Markers
Markers
You can use the keyword argument marker to emphasize each point with a specified
marker.
ypoints = [Link]([3,8,1,10])
ypoints = [Link]([3,8,1,10])
ypoints = [Link]([3,8,1,10])
[Link](ypoints, 'o:r')
[Link]()
o:r
o = Marker value ('o','*' etc)
: = Line value
r = Color reference
Line reference
Note: If you leave out the line value in the fmt parameter, no line will be plottet.
Color Reference
The short color value can be one of the following:
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:
Use both the mec and mfc arguments to color of the entire marker:
EXAMPLE: Set the color of both the edge and the face:
ypoints = [Link]([3,8,1,10])
Matplotlib Line:
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the
plotted line:
ypoints = [Link]([3,8,1,10])
Shorter Syntax
The line style can be written in a shorter syntax:
ypoints = [Link]([3,8,1,10])
[Link](ypoints, ls = ':')
[Link]()
Line Styles:
You can choose any of these styles
Line Color
You can use the keyword argument color or the shorter c to set the color of the line:
ypoints = [Link]([3,8,1,10])
[Link](ypoints, c = 'r')
[Link]()
Line Width
You can use the keyword argument linewidth or the shorter lw to change the width
of the line.
ypoints = [Link]([3,8,1,10])
Multiple Lines
You can plot as many lines as you like by simply adding more [Link]() functions:
Example: Draw two lines by specifying a [Link]() function for each line
y1 = [Link]([3,8,1,10])
y2 = [Link]([6,2,7,11])
[Link](y1)
[Link](y2)
[Link]()
You can also plot many lines by adding the points for the x- and y-axis for each line in
the same [Link]() 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 = [Link]([0,1,2,3])
x2 = [Link]([3,8,1,10])
x3 = [Link]([0,1,2,3])
x4 = [Link]([6,2,7,11])
[Link](x1,x2,x3,x4)
[Link]()
[Link](x,y)
[Link]("Average Pulse")
[Link]("Calorie Burnage")
[Link]()
EXAMPLE: Add a plot title and labels for the x- and y-axis
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link](x,y)
[Link]()
Set Font Properties for Title and Labels
You can use the fontdict parameter in xlabel(), ylabel(), and title()</font>, title() to set
font properties for the title and labels.
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
[Link](x,y)
[Link]()
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link](x,y)
[Link]()
Line Name
You can give the Name to your line by using legend function.
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link](x,y)
[Link](["Health Line"])
[Link]()
NOTE: You can change the position of the legend by giving arguments loc
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link](x,y)
[Link]()
[Link]()
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'.
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link](x,y)
[Link](axis = 'x')
[Link]()
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link]()
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link](x,y)
[Link]()
Always use the figure() function at starting.
Style:
With Matplotlib, we have styles which serve a very similar purpose to Matplotlib
graphs as CSS (cascading style sheet) pages serve for HTML.
The idea of a style page is to write your customization to a style file, and then, to use
those changes and apply them to your graph, all you do is import style and then use
that specific style.
First, you will need to import the style module from matplotlib:
Next, we specifiy what style we want to use. Matplotlib comes with a few styles
[Link]
In [31]: [Link]('ggplot')
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link]("ggplot")
[Link](x,y)
[Link]()
Immediately, we can tell the font is different, besides the title, the color of labels are
grey, and the axis background is a light grey. We also notice the grid is actually a solid
white line.
x = [Link]([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
[Link]("fivethirtyeight")
[Link](x,y)
[Link]()
You can see all of the available styles you currently have by doing:
In [34]: print([Link])
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'f
ivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind',
'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-mute
d', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-tal
k', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
You can choose any and use them.
Matplotlib Subplots:
Display Multiple Plots
With the subplots() function you can draw multiple plots in one figure:
#plot 1:
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](1, 2, 1)
[Link](x,y)
#plot 2:
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](1, 2, 2)
[Link](x,y)
[Link]()
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.
In [8]: [Link](1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
Out[8]: <AxesSubplot:>
In [37]: [Link](1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
Out[37]: <AxesSubplot:>
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:
#plot 1
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](2,1,1)
[Link](x,y)
#plo 2
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](2,1,2)
[Link](x,y)
[Link]()
You can draw as many plots you like on one figure, just descibe the number of rows,
columns, and the index of the plot.
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](2, 3, 1)
[Link](x,y)
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](2, 3, 2)
[Link](x,y)
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](2, 3, 3)
[Link](x,y)
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](2, 3, 4)
[Link](x,y)
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](2, 3, 5)
[Link](x,y)
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](2, 3, 6)
[Link](x,y)
[Link]()
Title
You can add a title to each plot with the title() function:
#plot 1
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](1,2,1)
[Link](x,y)
[Link]("SALES")
#plot 2
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](1,2,2)
[Link](x,y)
[Link]("INCOME")
[Link]()
Super Title
You can add a title to the entire figure with the suptitle() function:
#plot 1:
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](1, 2, 1)
[Link](x,y)
[Link]("SALES")
#plot 2:
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](1, 2, 2)
[Link](x,y)
[Link]("INCOME")
[Link]("MY SHOP")
[Link]()
Scatter:
Creating Scatter Plots
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:
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
[Link](x,y)
[Link]()
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.
Color
You can change the color of dots.
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
[Link](x,y, c= 'r' )
[Link]()
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
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?
[Link]()
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:
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
[Link](x, y, color = 'hotpink')
x = [Link]([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = [Link]([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
[Link](x, y, color = '#88c999')
[Link]()
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = [Link](["red","green","blue","yellow","pink","black","orange","purple","beige"
[Link](x, y, c=colors)
[Link]()
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:
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = [Link]([20,50,100,200,500,1000,60,90,10,300,600,800,75])
[Link](x,y, s= sizes)
[Link]()
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:
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = [Link]([20,50,100,200,500,1000,60,90,10,300,600,800,75])
[Link]()
You can use others function also for scatter plot that we used in line plot like title(),
xlabel()
Bars:
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
EXAMPLE:Draw 4 bars
[Link](x,y)
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.
x = ["APPLES", "BANANAS"]
y = [400, 350]
[Link](x,y)
[Link]()
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use the barh()
function:
[Link](x,y)
[Link]()
Bar Color
The bar() and barh() takes the keyword argument color to set the color of the bars:
x = [Link](['A','B','C','D'])
y = [Link]([3,8,1,10])
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
Bar Height
The barh() takes the keyword argument height to set the height of the bars:
Bar edge
You can chnage position of the bar by using align parameter.
Edge width
You can chnage the widtth of edge by using linewidth parameter.
[Link](figsize=(16,9))
[Link](x,y)
[Link]()
More than One data sets
Sometimes we have two or more sets to represent. For that you have to just use
another bar() function
x_index = [Link](len(x))
width = 0.2
[Link]()
But it overlap each ohter, we cant't get result properly.
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.
[Link](x)
[Link]()
a_student_age = [Link](18,45,(100))
b_student_age = [Link](15,40,(100))
print(a_student_age,'\n')
print(b_student_age)
[20 23 44 19 28 30 24 33 38 27 35 40 28 32 36 28 36 33 29 19 23 28 39 28
30 28 21 32 18 32 34 20 19 26 19 39 32 25 42 19 19 34 28 36 39 36 27 20
30 26 38 35 31 20 19 24 37 26 42 35 20 40 29 27 39 37 43 40 40 27 23 22
25 26 29 20 22 34 35 29 25 21 27 26 41 29 39 41 25 18 44 23 26 19 37 42
22 35 23 40]
[15 39 33 38 38 38 20 36 32 34 15 30 17 28 39 36 15 22 34 24 37 34 39 34
19 18 38 30 22 38 17 26 29 22 33 31 27 18 19 32 28 38 30 15 30 20 21 37
28 18 15 39 20 21 15 23 26 28 15 32 27 15 28 25 23 34 35 39 22 27 32 25
20 35 32 16 28 17 18 22 27 18 19 17 22 19 27 37 28 31 33 23 22 20 28 27
25 18 21 31]
In [58]: [Link](a_student_age)
[Link]("A Students age Histograms")
[Link]("Students age cotegory")
[Link]("No. Students age")
[Link]()
Histogram Parameters:
bins=None,
range=None,
density=False,
weights=None,
cumulative=False,
bottom=None,
histtype='bar',
align='mid',
orientation='vertical',
rwidth=None,
log=False,
color=None,
label=None,
stacked=False,
*,
data=None,
**kwargs,
bins:
This parameter is used to set the range of the bars.
arguments:{int or sequence or str, default: :rc: [Link] }
a_student_age = [Link](18,45,(100))
# To set the range of bar
bins = [15,20,25,30,35,40,45] # we set from 15 to 45 because our data is start from 15 and
[Link](a_student_age,bins)
[Link]()
density:
draw and return a probability density: each bin will display the bin's raw count divided
by the total number ofcounts and the bin width
[Link]()
rwidth:
To set the width of the bar, by default it is 1
[Link]()
histtype:
It changes the type of histogram
It has four arguments {'bar','barstacked','step','stepfilled'}
orientation:
To make graph horizonatl or vertical
arguments:{'vertical','horizontal}
By default it is vertical
[Link]()
color:
To set the colour of the bar.
[Link]()
Pie Charts:
Creating Pie Charts With Pyplot, you can use the pie() function to draw pie charts:
[Link](y)
[Link]()
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:
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:
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
Shadow
Add a shadow to the pie chart by setting the shadows parameter to True:
Example:Add a shadow
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:
text_properties = {"fontsize":20}
##----------------------------------------start
#[Link](3,2,1)
[Link](321)
#********************************************Line Plot
days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
delhi_tem = [36.6, 37, 37.7,39,40.1,43,43.4,45,45.6,40.1,44,45,46.8,47,47.8]
mumbai_tem = [39,39.4,40,40.7,41,42.5,43.5,44,44.9,44,45,45.1,46,47,46]
#---------------------------------------------------------------end
[Link](3,2,2) ##-------------------------------------------------start
#****************************************************************histograms
ml_students_age = [Link](18,45, (100))
py_students_age = [Link](15,40, (100))
bins = [15,20,25,30,35,40,45]
[Link](3,2,3) ##--------------------------------------------start
#************************************************************Bar Chart
classes = ["Python", "R", "AI", "ML", "DS"]
class1_students = [30, 10, 20, 25, 10] # out of 100 student in each class
class2_students = [40, 5, 20, 20, 10]
class3_students = [35, 5, 30, 15, 15]
classes_index = [Link](len(classes))
width = 0.2
[Link](3,2,4) ##------------------------------------------------start
#**************************************************************Scatter Plot
import [Link] as plt
import numpy as np
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = [Link]([20,50,100,200,500,1000,60,90,10,300,600,800,75])
[Link]()
#----------------------------------------------------------------------end
[Link](3,2,5) ##-----------------------------------------start
#*************************************************************Pie plot
classes = ["Python", 'R', 'Machine Learning', 'Artificial Intelligence',
'Data Sciece']
class1_students = [45, 15, 35, 25, 30]
explode = [0.03,0,0.1,0,0]
colors = ["c", 'b','r','y','g']
textprops = {"fontsize":5}
[Link](class1_students,
labels = classes,
explode = explode,
colors =colors,
autopct = "%0.2f%%",
shadow = True,
radius = 1.4,
startangle = 270,
textprops =textprops)
#------------------------------------------------------end
[Link]()
In [ ]: