Unit 9 Data Visualization with Matplotlib [2 hours]
Introduction; Marker; Line; Color; Label; Grid lines; Subplot; Scatter plot; Bar graph; Histogram, pie chart
and box plot.
Introduction:
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Matplotlib makes easy things easy and hard things possible.
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-
platform data visualization library built on NumPy arrays.
We can download matplotlib by using the following command;
python -mpip install -U matplotlib
pyplot:
[Link] is a collection of functions that make matplotlib work like MATLAB. Each pyplot
function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some
lines in a plotting area, decorates the plot with labels, etc.
Example:
import [Link] as plt
[Link]([1, 2, 3, 4])
[Link]('Numbers from 1 to 4')
[Link]()#display the graph
Output:
Description:
We may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If we provide a single list or
array to plot, matplotlib assumes it is a sequence of y values, and automatically generates the x values for
you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0;
therefore, the x data are [0, 1, 2, 3].
plot is a versatile function, and will take an arbitrary number of arguments. For example, to plot x versus y,
you can write: [Link]([1, 2, 3, 4], [1, 4, 9, 16])
'marker' in matplotlib:
You can use the keyword argument marker to emphasize each point with a specified marker.
Syntax:
[Link](ypoints, marker = 'o')
Example:
[Link]([1, 2, 3, 4], marker="o")
Output:
Marker points
Marker Reference: we can use the following markers in a marker attribute of plot function as:
[Link]([1, 2, 3, 4], marker="o")
Marker Shapes Markers Shapes
'o' Circle 'H' Hexagon
'*' Star 'h' Hexagon
'.' Point 'v' Triangle Down
',' Pixel '^' Triangle Up
'x' X '<' Triangle Left
'X' X (filled) '>' Triangle Right
'+' Plus '1' Tri Down
'P' Plus (filled) '2' Tri Up
's' Square '3' Tri Left
'D' Diamond '4' Tri Right
'd' Diamond (thin) '|' Vline
'p' Pentagon '_' Hline
Line Reference
Line Syntax Description
'-' Solid line-default
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line
Color Reference
Color Syntax Description
'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
Marker Size:
We can use the keyword argument markersize or the shorter version, ms to set the size of the markers:
Example:
import [Link] as plt
import numpy as np
ypoints = [Link]([3, 8, 1, 10])
[Link](ypoints, marker='H', ms=25)
[Link]()
Marker edge and face color:
Example:
import [Link] as plt
import numpy as np
ypoints = [Link]([3, 8, 1, 10])
[Link](ypoints, marker = 'o', ms = 20, mec = 'r', mfc = 'r')
[Link]()
Output:
Line;
We can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:
[Link](ypoints, linestyle="dotted")
[Link](ypoints, linestyle = 'dashed')
linestyle can be written as ls.
dotted can be written as :
dashed can be written as –
[Link](ypoints, color = 'r')#for coloring a line
[Link](ypoints, linewidth = '20.5')#for increasing the width of line
Drawing multiple lines:
Example:
import [Link] as plt
import numpy as np
x1 = [Link]([0, 1, 2, 3])
y1 = [Link]([3, 8, 1, 10])
x2 = [Link]([0, 1, 2, 3])
y2 = [Link]([6, 2, 7, 11])
[Link](x1, y1, x2, y2)
[Link]()
Label;
import numpy as np
import [Link] as plt
xover = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
yrr = [Link]([10, 25, 30, 35, 55, 63, 67, 75, 89, 102])
[Link](xover, yrr, marker="H", color="r", linewidth="5", mec="g", mfc="b")
ycsk = [Link]([10, 30, 35, 42, 52, 60, 74, 84, 100, 106])
[Link](xover, ycsk, marker="o", color="b", linewidth="5", mec="r", mfc="g")
[Link]("Overs")
[Link]("Runs -Red=R Blue=CSK")
[Link]()
Set Font Properties for Title and Labels
We can use the fontdict parameter in xlabel(), ylabel(), and title() to set font properties for the title and
labels.
Example:
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
[Link]("IPL 2023 CSK Vs RR", fontdict = font1)
[Link]("Overs", fontdict = font2)
[Link]("Runs -Red=R Blue=CSK", fontdict = font2)
Position the Title
We can use the loc parameter in title() to position the title. Legal values are: 'left', 'right', and 'center'. Default
value is 'center'.
Example:
[Link]("IPL 2023 CSK Vs RR", loc = 'left')
Grid lines;
With Pyplot, you can use the grid() function to add grid lines to the plot.
The [Link]() function adds gridlines to the graph and [Link](axis='x') and [Link](axis='y'), adds grids to
x coordinate and y coordinate respectively.
We can specify the color, linewidth and type of gridlines by using following properties;
[Link](color = 'green', linestyle = '--', linewidth = 0.5)
Subplot;
Display Multiple Plots using subplot function in matplotlib.
With the subplot() function you can draw multiple plots in one figure. 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.
[Link](1, 2, 1)
#the subplot(1, 2, 1) means output figure has 1 row, 2 columns, and this plot is the first plot.
[Link](1, 2, 2)
#the subplot(1, 2, 2) means output figure has 1 row, 2 columns, and this plot is the second plot.
So, if we want a figure with 2 rows and 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:
import [Link] as plt
import numpy as np
#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]()
Scatter plot;
With Pyplot, we can use the scatter() function instead of plot 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:
Example:
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])
[Link](x, y)
[Link]()
We can use two different scatter points with different colors as;
[Link](x, y, color = 'red')
Bar graph;
For bar diagram matplotlib provides a bar() function that creates a bar diagram in a graph. For changing the
width of bars we can use attribute as;
[Link](x, y, width = 0.1)
Example:
import [Link] as plt
import numpy as np
x = [Link](["A", "B", "C", "D"])
y = [Link]([3, 8, 1, 10])
[Link](x, y, color = "#4CAF50")# for horizontal bar we have [Link]() function.
[Link]()
Histogram,
A histogram is a graph showing frequency distributions. The hist() function will read the array and produce
a histogram. The hist() function will use an array of numbers to create a histogram, the array is sent into the
function as an argument.
Example:
import [Link] as plot
# grades in mathematics
math__score = [54, 37, 57, 43, 72, 43, 91, 43, 93, 49,
60, 69, 62, 73, 42, 63, 82, 83, 81, 33,
70, 50, 81, 69, 87, 45, 85, 55, 53, 60,
53, 66, 53, 79, 79, 69, 55, 87, 66, 49,
73, 41, 75, 60, 90, 50, 44, 47, 78, 79,
78, 48, 84, 68, 56, 64, 83, 48, 86, 63,
59, 87, 42, 68, 47, 98, 52, 72, 62, 66,
83, 47, 34, 84, 64, 98, 95, 57, 82, 52,
56, 74, 84, 83, 65, 31, 89, 75, 79, 77,
78, 68, 78, 48, 88, 62, 88, 74, 74, 78]
# display the histogram
[Link](math__score)
[Link]()
Output:
Pie chart and box plot.
With Pyplot, you can use the pie() function to draw pie charts.
Example:
import [Link] as plt
import numpy as np
y = [Link]([35, 25, 25, 15])
[Link](y)
[Link]()
For making pie more attractive or informative we use certain attributes as follows;
1. mylabels = ["Nepali", "English", "Maths", "Science"]
[Link](y, labels = mylabels)
2. [Link](y, labels = mylabels, startangle = 90)
3. [Link](y, labels = mylabels, explode = myexplode): for cutting pie into
different pieces.
4. [Link](y, labels = mylabels, explode = myexplode, shadow = True): for
displaying pie just like 3D.
5. [Link](y, labels = mylabels)
[Link](title="Subjects"): to display the color corresponding with colors.