1. Basic plots

1.1. Introduction

In this tutorial, Matplotlib library is discussed in detail, which is used for plotting the data. Our aim is to introduce the commonly used ‘plot styles’ and ‘features’ of the Matplotlib library, which are required for plotting the results obtained by the simulations or visualizing the data during machine learning process.

1.2. Data generation with Numpy

In this tutorial, Numpy library is used to generate the data for plotting. For this purpose, only 5 functions of numpy library are used, which are shown in Listing 1.1,

Listing 1.1 Data generation using Numpy
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#numpyDataEx.py
# import numpy library with short name `np'
# outputs are shown as comments
import numpy as np

# 1. linspace(a, b, total_points)
x = np.linspace(2, 8, 4) 
print(x) # [ 2.  4.  6.  8.]

# 2. sin(x)
sinx = np.sin(x) # x is consider as radian
print(sinx) # [ 0.90929743 -0.7568025  -0.2794155   0.98935825]

# 3. cos(x)
cosx = np.cos(x)
print(cosx) #[-0.41614684 -0.65364362  0.96017029 -0.14550003]

# 4. rand: uniform random variables
ur = np.random.rand(4) # result below will be different as it is random
print(ur) # [ 0.99791448  0.95621806  0.48124676  0.20909043]

# 5. randn: normal random variables
nr = np.random.randn(4) # result below will be different as it is random
print(nr) # [-0.37188868 -0.5680135  -0.21731407 -0.69523557]

1.3. Basic Plots

In this section, basic elements of the plot e.g. Title, axis names and grid etc. are discussed.

1.3.1. First Plot

Listing 1.2 plots the sin(x) as shown in Fig. Fig. 1.1.

  • Explanation Listing 1.2

    Here, line 8 generates 100 equidistant points in the range \([-2\pi, 2\pi]\). Then line 9 calculates the sine values for those points. Line 10 plots the figure, which is displayed on the screen using line 11.

Listing 1.2 Sin(x), Fig. Fig. 1.1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#firstPlot.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)
plt.plot(x,sinx) #plot x on x-axis and sin_x on y-axis
plt.show() #display the plot
../_images/firstPlot.png

Fig. 1.1 fig_firstPlot

1.3.2. Label, Legend and Grid

Here Listing 1.2 is modified as shown in Listing 1.3, to add labels, legend and grid to the plot.

  • Explanation Listing 1.3

    In line 11, label=’sin’ is added which is displayed by ‘legend’ command in line 15. ‘loc=best’ is optional parameter in line 15. This parameter find the best place for the legend i.e. the place where it does not touch the plotted curve. Line 18 and 19 add x and y label to curves. Finally, line 21 adds the grid-lines to the plot.

    For changing the location of legend, replace ‘best’ in line 15 with ‘center’, ‘center left’, ‘center right’, ‘lower center’, ‘lower left’, ‘lower right’, ‘right’, ‘upper center’, ‘upper left’ or ‘upper right’.

Listing 1.3 Grid, Label and Legend, Fig. 1.2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#firstPlotGL.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

############ Sin(x) ####################
x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)
plt.plot(x,sinx, label='sin')

############ Legend ####################
# label in plt.plot are displayed by legend command 
plt.legend(loc="best") #show legend

#### Lable and Grid ####################
plt.xlabel("Radian") # x label 
plt.ylabel("Amplitude") # y label

plt.grid() # show grid

plt.show() #display the plot
../_images/firstPlotGL.png

Fig. 1.2 Grid, Axes, Label and Legend, Listing 1.3

1.3.3. Line style and Marker

It is good to change the line styles and add markers to the plots with multiple graphs. It can be done as shown in Listing 1.4.

  • Explanation Listing 1.4

    In line 13, ‘*–r’ is the combination of three separate parameters i.e. ‘*’, ‘–’ and ‘r’, which represents ‘marker’, ‘line style’ and ‘color’ respectively. We can change the order of these combinations e.g. ‘r–*’ and ‘–r*’ etc. Also, combination of two parameters (e.g. ‘r–’) or single parameter (e.g. ‘–’) are valid.

    Table Table 1.1, Table 1.2 and Table 1.3 show some more abbreviations for ‘line style’, ‘marker style’ and ‘color’ respectively. Note that, only one element can be chosen from each style to make the combination.

    Further, line 13 contains ‘markersize’ parameter for changing the size of the marker. Table Table 1.4 shows the complete list of additional parameters to change the plot style. Lastly, line 13 can be rewritten using complete features of the plot as follows,

    plt.plot(x, sinx, color='m',
        linestyle='-.', linewidth=4,
         marker='o', markerfacecolor='k', markeredgecolor='g',
         markeredgewidth=3, markersize=5,
        label='sin'
    )
    
Listing 1.4 Line Style and Marker, Fig. 1.3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#firstPlotLineMarker.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

############ Sin(x) ####################
x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)

########### Line style and Marker ###################
plt.plot(x,sinx, '*--r', markersize=10, label='sin')  

############ Legend ####################
plt.legend(loc="best") #show legend

#### Lable and Grid ####################
plt.xlabel("Radian") # x label 
plt.ylabel("Amplitude") # y label
plt.grid() # show grid

plt.show() #display the plot
../_images/firstPlotLineMarker.png

Fig. 1.3 Line-style and Line-marker, Listing 1.4

Table 1.1 Line styles
Keyword Description
-. dash-dot line
dashed line
: dotted line
- solid line
Table 1.2 Marker styles
Keyword Description
o circle
x cross
D diamond
h hexagon
p pentagon
+ plus
. dot
s square
* star
V down triangle
< left triangle
> right triangle
^ up triangle
Table 1.3 Color styles
Keyword Description
k black
b blue
c cyan
g green
m magenta
r red
w white
y yellow
Table 1.4 Plot styles
   
color set the color of line
linestyle set the line style
linewidth set the line width
marker set the line-marker style
markeredgecolor set the marker edge color
markeredgewidth set the marker edge width
markerfacecolor set the marker face color
markersize set the marker size

1.3.4. Axis and Title

Listing 1.5 adds axis and title in previous figures.

  • Explanation Listing 1.5

    Lines 25 and 26 in the listing add display range for x and y axis respectively in the plot as shown in Fig. 1.4. Line 30 and 32 add the ticks on these axis. Further, line 31 adds various ‘display-name’ for the ticks. It changes the display of ticks e.g. ‘np.pi’ is normally displayed as ‘3.14’, but \(r'$+\backslash pi$\) will display it as \(+\pi\). Note that \(\backslash pi\) is the ‘latex notation’ for \(\pi\), and matplotlib supports latex notation as shown in various other examples as well in the tutorial.

Listing 1.5 Title and Axis, Fig. 1.4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#completeBasicEx.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

############ Sin(x) ####################
x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)

########### Line style and Marker ###################
plt.plot(x,sinx, '*--r', markersize=10, label='sin')  

############ Legend ####################
plt.legend(loc="best") #show legend

#### Lable and Grid ####################
plt.xlabel("Radian") # x label 
plt.ylabel("Amplitude") # y label
plt.grid() # show grid

############ Axis Limit and Marker ##################
# x-axis and y-axis limits
plt.xlim([-2*np.pi, 2*np.pi]) # x-axis display range
plt.ylim([-1.5, 1.5]) # y-axis display range

# ticks on the axis
# display ticks in pi format rather than 3.14 format
plt.xticks([-2*np.pi, -np.pi, 0, np.pi, 2*np.pi],
          [r'$-2\pi$', r'$-\pi$', r'$0$', r'$+\pi$', r'2$\pi$'])
plt.yticks([-1, 0, +1])

################## Title #########################
plt.title("Plot $Sin(x)$")

plt.show()
../_images/completeBasicEx.png

Fig. 1.4 Axis-limit and Axis-marker, Listing 1.5

1.4. Multiple Plots

In this section various mutliplots are discussed e.g. plots on the same figure window and subplots etc.

1.4.1. Mutliplots in same window

By default, matplotlib plots all the graphs in the same window by overlapping the figures. In Listing 1.6, line 14 and 15 generate two plots, which are displayed on the same figure window as shown in Fig. 1.5.

Listing 1.6 Mutliplots in same window, Fig. 1.5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#multiplot.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

############ Sin(x) ####################
x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)
cosx=np.cos(x) # calculate cos(x)

########### Line style and Marker ###################
plt.plot(x,sinx, '*--r', label='sin')  
plt.plot(x,cosx, 'o-g', label='cos') 

############ Legend ####################
plt.legend(loc="best") #show legend

#### Lable and Grid ####################
plt.xlabel(r'$Radian$').set_fontsize(16) # x label 
plt.ylabel(r'$Amplitude$').set_fontsize(16) # y label
plt.grid() # show grid

plt.show()
../_images/multiplot.png

Fig. 1.5 Multiplots, Listing 1.6

1.4.2. Subplots

In Fig. 1.5, two plots are displayed in the same window. Further, we can divide the plot window in multiple sections for displaying each figure in different section as shown in Fig. 1.6

  • Explanation Listing 1.7

    Subplot command takes three parameters i.e. number of rows, numbers of columns and location of the plot. For example in line 14, subplot(2,1,1), divides the figure in 2 rows and 1 column, and uses location 1 (i.e. top) to display the figure. Similarly, in line 21, subplot(2,1,2) uses the location 2 (i.e. bottom) to plot the graph. Further, Listing 2.2 divides the figure window in 4 parts and then location 1 (top-left), 2 (top-right), 3 (bottom-left) and 4 (bottom-right) are used to display the graphs.

    Also, all the plot commands between line 14 and 21, e.g. line 15, will be displayed on the top location. Further, plots defined below line 21 will be displayed by bottom plot window.

Listing 1.7 Subplots, Fig. 1.6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#subplotEx.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

############ Sin(x) ####################
x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)
cosx=np.cos(x) # calculate cos(x)

########### Subplot ###################
plt.subplot(2,1,1)
plt.plot(x,sinx, '*--r', label='sin')
plt.grid() # show grid
plt.legend() #show legend
plt.xlabel(r'$Radian$')# x label 
plt.ylabel(r'$Amplitude$') # y label

plt.subplot(2,1,2)
plt.plot(x,cosx, 'o-g', label='cos') 
plt.grid() # show grid
plt.legend() #show legend
plt.xlabel(r'$Radian$') # x label 
plt.ylabel(r'$Amplitude$') # y label
############ Legend ####################

#### Lable and Grid ####################
plt.xlabel(r'$Radian$') # x label 
plt.ylabel(r'$Amplitude$') # y label


plt.show()
../_images/subplotEx.png

Fig. 1.6 Subplots, Listing 1.7

1.4.3. Mutliplots in different windows

‘figure()’ command is used to plot the graphs in different windows, as shown in line 17 of Listing 1.8.

  • Explanation Listing 1.8

    Here optional name ‘Sin’ is given to the plot which is displayed on the top in Fig. 1.7. Then line 19 opens a new plot window with name ‘Cos’ as shown in Fig. 1.8. Finally in line 21, the name ‘Sin’ is used again, which selects the previously open ‘Sin’ plot window and plot the figure there. Hence, we get two plots in this window (i.e. from lines 18 and 22) as show in Fig. 1.7.

Listing 1.8 Mutliplots in different windows, Fig. 1.7 and Fig. 1.8
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#multiplotDifferentWindow.py
import numpy as np
import matplotlib.pyplot as plt

# close all the figures, if open from previous commands
plt.close('all') 

############ Sin(x) ####################
x=np.linspace(-2*np.pi, 2*np.pi, 100) 
sinx=np.sin(x) # calculate sin(x)
cosx=np.cos(x) # calculate cos(x)

########### Open figure in seperate window ###################
#"Sin" is the name of figure window
# if not give i.e. plt.figure(), then 1 will be assigned to figure
# and for second plt.figure(), 2 will be assigned...
plt.figure("Sin") 
plt.plot(x,sinx, '*--r', label='sin')  
plt.figure("Cos")
plt.plot(x,cosx, 'o-g', label='cos') 
plt.figure("Sin")
plt.plot(x,cosx, 'o-g', label='cos') 

############ Legend ####################
plt.legend(loc="best") #show legend

#### Lable and Grid ####################
plt.xlabel(r'$Radian$').set_fontsize(16) # x label 
plt.ylabel(r'$Amplitude$').set_fontsize(16) # y label
plt.grid() # show grid

plt.show()
../_images/multiplotDifferentWindow.png

Fig. 1.7 Figure window with name ‘Sin’

../_images/multiplotDifferentWindow2.png

Fig. 1.8 Figure window with name ‘Cos’