You are on page 1of 21

Graphics Matlab Approach OOP Approach Further Readings

(1) Graphics: matplotlib and seaborn modules


 Simple line plots, scatter plots, histograms, bar plots and pie plots.
 Multiple subplots

(2) References:
 https://matplotlib.org/
 https://seaborn.pydata.org/

1 / 21
Graphics Matlab Approach OOP Approach Further Readings

Anatomy of a figure

4
Anatomy of a figure
Title Blue signal
Major tick Red signal
Legend
Minor tick
3
Major tick label Grid
Line
(line plot)
Y axis label

2
Markers
Y axis label (scatter plot)

Spines
Line
(line plot)
0
0 0.25 0.50 0.75 1 1.25 1.50 1.75 2 2.25 2.50 2.75 3 3.25 3.50 3.75 4
Minor tick label X axis label Made with http://matplotlib.org
X axis label

2 / 21
Graphics Matlab Approach OOP Approach Further Readings

Plotting

Anatomy: Title, Legend, Line, Markers, Grid, Y axis label, X


axis label, Major tick, Minor tick, Major tick label, Minor tick
label, Spines.
For graphics, we need the following modules:
import matplotlib . pyplot as plt
import seaborn as sns

Matplotlib was originally written as a Python alternative for MATLAB users,


and much of its syntax reflects that fact. The MATLAB-style tools are
contained in the pyplot (plt) interface.
To create a figure, matplotlib provides two approaches:
1 A convenient MATLAB-style approach.
2 An object-oriented programming (OOP) approach.

For more simple plots, the choice of which approach to use is largely a matter of
preference. In complicated situations, the OOP approach has more advantages.
Seaborn offers plot style and color defaults.

3 / 21
Graphics Matlab Approach OOP Approach Further Readings

Setting a style

Using seaborn, we can set a style for our figure in the following way.
# Setting style
# There are five preset seaborn themes :
# sns . set ( style = ' whitegrid ' )
# sns . set ( style = ' dark ' )
# sns . set ( style = ' white ' )
# sns . set ( style = ' ticks ' )
sns . set ( style = ' darkgrid ' ) # seaborn theme for the background

Alternatively, we can use plt.style to choose appropriate aesthetic styles for


our figures:
# An alternative way to set style
plt . style . use ( ' seaborn - darkgrid ' )

To see all availabe styles, use:


In [21]: print ( plt . style . available )
[ ' bmh ' , ' classic ' , ' dark_background ' , ' fast ' , ' fivethirtyeight ' , ' ggplot ' , ' grayscale ' ,
' seaborn - bright ' , ' seaborn - colorblind ' , ' seaborn - dark - palette ' , ' seaborn - dark ' ,
' seaborn - darkgrid ' , ' seaborn - deep ' , ' seaborn - muted ' , ' seaborn - notebook ' ,
' seaborn - paper ' , ' seaborn - pastel ' , ' seaborn - poster ' , ' seaborn - talk ' ,
' seaborn - ticks ' , ' seaborn - white ' , ' seaborn - whitegrid ' , ' seaborn ' ,
' Sol ariz e_Light2 ' , ' tableau - colorblind10 ' , ' _classic_test ' ]

4 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

Using plt.plot() function, we can produce the following plots.


# Data
y = np . random . randn (100)
x = np . cumsum ( np . random . rand (100))
# Plot 1
plt . plot ( y )
# Plot 2
plt . plot (y , ' r - o ' , label = ' a line graph ' )
plt . legend ()
plt . xlabel ( ' x label ' )
plt . title ( ' A line plot ' )
plt . ylabel ( ' y label ' )
# Plot 3
plt . plot (x ,y , ' r - d ' , label = ' a line graph ' )
plt . legend ()
plt . xlabel ( ' x label ' )
plt . title ( ' USING PLOT ' )
plt . ylabel ( ' y label ' )

In Plot 2, r-o indicates red (r), solid line (-) and circle (o) marker. Similarly, in
Plot 3, r-d indicates color red (r), solid line (-) and diamond (d) marker.
Titles are added with title() and legends are added with legend(). The
legend requires that the line has a label.
The labels for the x and y axis are added by xlabel() and ylabel().

5 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

(a) Plot 1 (b) Plot 2

(c) Plot 3

6 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

Now we will specify the arguments of plt.plot() explicitly in the following


example.
In [22]: plt . plot (x ,y , alpha = 1 , color = ' # FF7F00 ' , \
...: label = ' Line Label ' , linestyle = ' - ' , \
...: linewidth = 2 , marker = ' o ' , markeredgecolor = ' #000000 ' , \
...: markeredgewidth = 1 , markerfacecolor = ' # FF7F99 ' , \
...: markersize =5)
...: plt . legend ()
...: plt . xlabel ( ' x label ' )
...: plt . title ( ' USING PLOT ' )
...: plt . ylabel ( ' y label ' )

7 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

The most useful keyword arguments of plt.plot() are listed in the table
below.

Table 1: Keyword arguments for plt.plot()


alpha Alpha (transparency) of the plot- default is 1 (no transparency)
color Color description for the line
label Label for the line- used when creating legends
linestyle A line style symbol
linewidth A positive integer indicating the width of the line
marker A marker shape symbol or character
markeredgecolor Color of the edge (a line) around the marker
markeredgewidth Width of the edge (a line) around the marker
markerfacecolor Face color of the marker
markersize A positive integer indicating the size of the marker

8 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

Some options for color, linestyle and marker are given in the following
table.

Table 2: Options for color, linestyle and marker


color linestyle marker
blue: b Solid: - Point: ·
green: g dashed: - pixel: ,
red: r dashdot: -. circle: o
cyan: c dotted: : square: s
magenta: m diamond: D
yellow: y thin diamond: d
black: k cross: x
white: w plus: +
star: *
hexagon: H
alt. hexagon: h
pentagon: p
triangles: ^,v,<,>
vertical line: |
horizontal line: _

9 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots
Alternative ways to specify colors and line-styles:
# Alternative ways to specify colors
x = np . linspace (0 , 10 , 1000)
plt . plot (x , np . sin ( x - 0) , color = ' blue ' ) # specify color by name
plt . plot (x , np . sin ( x - 1) , color = ' g ' ) # short color code ( rgbcmyk )
plt . plot (x , np . sin ( x - 2) , color = ' 0.2 ' ) # Grayscale between 0 and 1
plt . plot (x , np . sin ( x - 3) , color = ' # FFDD44 ' ) # Hex code ( RRGGBB from 00 to FF )
plt . plot (x , np . sin ( x - 4) , color =(1.0 ,0.2 ,0.3)) # RGB tuple , values 0 and 1
plt . plot (x , np . sin ( x - 5) , color = ' chartreuse ' ); # all HTML color names supported
# Alternative way to specify linestyle
plt . plot (x , x + 0 , linestyle = ' solid ' )
plt . plot (x , x + 1 , linestyle = ' dashed ' )
plt . plot (x , x + 2 , linestyle = ' dashdot ' )
plt . plot (x , x + 3 , linestyle = ' dotted ' );

(d) Colors (e) Line styles

10 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

The functions getp() and setp() can be used to get the list of properties for
a line (or any matplotlib object), and setp() can also be used to set a
particular property.

The functions getp() and setp() can be used in the following way.
# Using setp ()
h = plot ( randn (10))
setp (h , alpha =0.5 , linestyle = ' -- ' , linewidth =2 , label = ' Line Label ' ,\
marker = ' o ' , color = ' red ' )
plt . legend ()
plt . xlabel ( ' x label ' )
plt . title ( ' USING PLOT ' )
plt . ylabel ( ' y label ' )
# If you want to see all the properties that can be set ,
# and their possible values , you can do :
getp ( h )
# If you want to know the valid types of arguments , you can provide the name of
# the property you want to set without a value :
setp (h , ' alpha ' )
setp (h , ' color ' )
setp (h , ' linestyle ' )
setp (h , ' marker ' )

11 / 21
Graphics Matlab Approach OOP Approach Further Readings

Line plots

To set axes limit, we can use plt.xlim() and plt.ylim().


x = np . linspace (0 , 10 , 1000)
plt . plot (x , np . sin ( x ))
plt . xlim ( -1 , 11)
plt . ylim ( -1.5 , 1.5)

We can also use plt.axis() to set or get some axis properties.


# plt . axis () method allows you to set the x
# and y limits with a single call : [ xmin , xmax , ymin , ymax ]
plt . plot (x , np . sin ( x ))
plt . axis ([ -1 , 15 , -1.5 , 1.5])

12 / 21
Graphics Matlab Approach OOP Approach Further Readings

Scatter, bar, pie and histogram plots

# Scatter plots
z = np . random . randn (100 ,2)
z [: ,1] = 0.5* z [: ,0] + sqrt (0.5)* z [: ,1]
x = z [: ,0]
y = z [: ,1]
plt . scatter (x ,y , c = ' # FF7F99 ' , marker = ' o ' , \
alpha = 1 , label = ' Scatter Data ' )
# Bar plots
y = np . random . rand (5)
x = arange (5)
b = plt . bar (x ,y , width = 1 , color = ' # FF7F99 ' , \
edgecolor = ' #000000 ' , linewidth = 1)
# Pie plots
y = np . random . rand (5)
y = y / sum ( y )
y [y <.05] = .05
labels =[ ' One ' , ' Two ' , ' Three ' , ' Four ' , ' Five ' ]
colors = [ ' # FF0000 ' , ' # FFFF00 ' , ' #00 FF00 ' , ' #00 FFFF ' , ' #0000 FF ' ]
plt . pie (y , labels = labels , colors = colors )
# Histograms
x = np . random . randn (1000)
plt . hist (x , bins = 30)
plt . hist (x , bins = 30 , density = True , color = ' # FF7F00 ' )

13 / 21
Graphics Matlab Approach OOP Approach Further Readings

Scatter, bar, pie and histogram plots

(f) Scatter plot (g) Bar plot

(h) Pie plot (i) Histogram

14 / 21
Graphics Matlab Approach OOP Approach Further Readings

Multiple plots on the same figure


For adding a subplot to the current figure, we can use plt.subplot().
# Panel 1
plt . subplot (2 ,2 ,1)
y = np . random . randn (100)
plt . plot ( y )
plt . title ( ' Plot 1 ' )
# Panel 2
y = np . random . rand (5)
x = np . arange (5)
plt . subplot (2 ,2 ,2)
plt . bar (x ,y , label = ' Bar Chart ' )
plt . legend ()
plt . xlabel ( ' x label ' )
plt . title ( ' USING PLOT ' )
plt . ylabel ( ' y label ' )
# ax . set_title ( ' Plot 2 ' )
# Panel 3
y = np . random . rand (5)
y = y / sum ( y )
y [y <.05] = .05
plt . subplot (2 ,2 ,3)
plt . pie ( y )
plt . title ( ' Plot 3 ' )
# Panel 4
z = np . random . randn (100 ,2)
z [: ,1] = 0.5* z [: ,0] + np . sqrt (0.5) * z [: ,1]
x = z [: ,1]
y = z [: ,1]
plt . subplot (2 ,2 ,4)
plt . scatter (x , y )
plt . title ( ' Plot 4 ' )
plt . xlabel ( ' x values ' )
plt . ylabel ( ' y values ' )

15 / 21
Graphics Matlab Approach OOP Approach Further Readings

Multiple Plots on the Same Axes

# Multiple Plots on the Same Axes


x = np . random . randn (100)
plt . figure ()
plt . hist (x , bins = 30 , density = True , label = ' Empirical ' )
pdfx = np . linspace ( x . min () , x . max () ,200)
pdfy = stats . norm . pdf ( pdfx )
plt . plot ( pdfx , pdfy , ' r - ' , label = ' PDF ' )
plt . legend ()

16 / 21
Graphics Matlab Approach OOP Approach Further Readings

The object-oriented interface is available for more complicated situations, and


for when you want more control over your figure.
In the object-oriented approach, the plotting functions are methods of explicit
Figure and Axes objects.
For all Matplotlib plots, we start by creating a figure and an axes. In their
simplest form, a figure and axes can be created as follows
fig = plt . figure ()
ax = plt . axes ()
In [124]: type ( fig )
Out [124]: matplotlib . figure . Figure
In [125]: type ( ax )
Out [125]: matplotlib . axes . _subplots . AxesSubplot

fig (an instance of the class plt.Figure) can be thought of as a single container
that contains all the objects representing axes, graphics, text, and labels.
ax (an instance of the class plt.Axes): a bounding box with ticks and labels,
which will eventually contain the plot elements that make up our visualization.

17 / 21
Graphics Matlab Approach OOP Approach Further Readings

OOP Approach

# Plot 1
fig = plt . figure ()
ax = plt . axes ()
x = np . linspace (0 , 10 , 1000)
ax . plot (x , np . sin ( x ) , color = ' r ' )

Figure 1: Plot 1

18 / 21
Graphics Matlab Approach OOP Approach Further Readings

While most plt functions translate directly to ax methods (such as


plt.plot()→ ax.plot(), plt.legend()→ ax.legend(), etc.), this is not
the case for all commands.
1 plt.plot() → ax.plot()
2 plt.legend() → ax.legend()
3 plt.xlabel() → ax.set_xlabel()
4 plt.ylabel() → ax.set_ylabel()
5 plt.xlim() → ax.set_xlim()
6 plt.ylim() → ax.set_ylim()
7 plt.title() → ax.set_title()
8 plt.subplot() → ax.fig.add_subplot()

In the OOP approach, rather than calling these functions individually, it is often
more convenient to use the ax.set()
# Plot 2
ax = plt . axes ()
ax . plot (x , np . sin ( x ))
ax . set_title ( ' A Simple Plot ' )
ax . set_xlabel ( ' x ' )
ax . set_ylabel ( ' sin ( x ) ' )
ax . set_xlim (0 ,10)
ax . set_ylim ( -2 ,2)
# Plot 3
ax = plt . axes ()
ax . plot (x , np . sin ( x ))
ax . set ( xlim =(0 , 10) , ylim =( -2 , 2) ,
xlabel = ' x ' , ylabel = ' sin ( x ) ' , title = ' A Simple Plot ' )

19 / 21
Graphics Matlab Approach OOP Approach Further Readings

Scatter, bar, pie and histogram plots


# Plot 4
x = np . linspace (0 , 10 , 1000)
ax = plt . axes ()
ax . plot (x , np . sin ( x ) , label = ' sin ( x ) ' )
ax . plot (x , np . cos ( x ) , label = ' cos ( x ) ' )
ax . set ( xlim =(0 , 10) , ylim =( -2 , 2) ,
xlabel = ' x ' , ylabel = ' y ' , title = ' A Simple Plot ' )
ax . legend ()

(a) Plot 2 (b) Plot 3

(c) Plot 4
20 / 21
Graphics Matlab Approach OOP Approach Further Readings

Further Readings

The major resources for matplotlib can be found on the Web.


The home page of matplotlib: http://matplotlib.org.
A gallery with many useful examples: http://matplotlib.org/gallery.html.
A tutorial for 2D plotting:
http://matplotlib.org/users/pyplot_tutorial.html.
A tutorial for 3D plotting:
http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html.

21 / 21

You might also like