# Matplotlib Guide¶

## Basic plots¶

### 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.

### 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,

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] 

### Basic Plots¶

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

#### 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.

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 

#### 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’.

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 

#### 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'
)

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 
Line styles
Keyword Description
-. dash-dot line
dashed line
: dotted line
- solid line
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
Color styles
Keyword Description
k black
b blue
c cyan
g green
m magenta
r red
w white
y yellow
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

#### 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.

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() 

### Multiple Plots¶

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

#### 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.

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() 

#### 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.

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() 

#### 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.

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() 

## Plot types¶

In this chapter, various plot types are discussed.

### Semilog Plot¶

Semilog plots are the plots which have y-axis as log-scale and x-axis as linear scale as shown in Fig. 2.2. Listing 2.1 plots both the semilog and linear plot of the function $$e^x$$.

Linear plot (Fig. 2.1) vs Semilog plot (Fig. 2.2)
  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 #semilogEx.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(0.01, 5, 100) e=np.exp(x) #linear plot plt.plot(x,e) plt.xlabel("x") plt.ylabel("y=exp(x)") plt.title("Linear Y axis") #semilog plot #log(exp(x))=x therefore straight line will be displayed plt.figure() plt.semilogy(x,e) #semilogy: semilog y-axis plt.xlabel("x") plt.ylabel("y=exp(x)") plt.title("Log Y axis") plt.show() #display the plot 

### Histogram¶

Histogram can be generated using hist() command as illustrated in line 11 in Listing 2.2. By default it generates 10 bins, which can be increased by providing the number of bins as shown in line 15. Further from Fig. 2.3, we can see that ‘rand’ generates the random number in the range [0,1] with uniform density, whereas ‘randn’ generates the random number in the range [-1,1] with Gaussian (Normal) density.

Histogram, Fig. 2.3
  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 #histogramEx.py import numpy as np import matplotlib.pyplot as plt plt.close("all") ur = np.random.rand(10000) nr = np.random.randn(10000) plt.subplot(2,2,1) plt.hist(ur) plt.xlabel("Uniform Random Number, Default 10 Bin") plt.subplot(2,2,2) plt.hist(ur, 20) # display 20 bins plt.xlabel("Uniform Random Number, 20 Bin") plt.subplot(2,2,3) plt.hist(nr) plt.xlabel("Normal Random Number, Default 10 Bin") plt.subplot(2,2,4) plt.hist(nr, 20) # display 20 bins plt.xlabel("Normal Random Number, 20 Bin") plt.show() 

### Scatter plot¶

Scatter plots are similar to simple plots and often use to show the correlation between two variables. Listing 2.3 generates two scatter plots (line 14 and 19) for different noise conditions, as shown in Fig. 2.4. Here, the distortion in the sine wave with increase in the noise level, is illustrated with the help of scatter plot.

Scatter plot, Fig. 2.4
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #scatterEx.py import numpy as np import matplotlib.pyplot as plt plt.close("all") N=100 x = np.linspace(0, 2*np.pi, N) noise = np.random.randn(N) signal = 2*np.sin(x) y = signal + noise plt.plot(x, signal) # signal + noise plt.scatter(x, y) #scatter plot plt.figure() y = signal + 0.2*noise # singal + 0.2*noise i.e. low noise plt.plot(x, signal) plt.scatter(x, y) #scatter plot plt.show() 

### Pie chart¶

Here, pie charts are generated in two formats. Listing 2.4 generates a simple Pie chart with data names as show in Fig. 2.5. Also in line 9, figsize=(5,5) command is used here, to resize the output figure window. Further, Listing 2.5 adds additional features (line 13) to it i.e. explode and auto-percentage as shown in Fig. 2.6.

Pie chart, Fig. 2.5
  1 2 3 4 5 6 7 8 9 10 11 12 #pieEx.py import matplotlib.pyplot as plt plt.close("all") x = [30, 20, 15, 25, 10] dataName = ['data1', 'data2', 'data3', 'data4', 'data5'] plt.figure(figsize=(5,5)) #figsize: output figure window size plt.pie(x, labels=dataName) plt.show() 
Pie chart: explode and auto-percentage, Fig. 2.6
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 #pieEx2.py import matplotlib.pyplot as plt plt.close("all") x = [10, 10, 20, 20, 30] dataName = ['data1', 'data2', 'data3', 'data4', 'data5'] explode = [0.01, 0, 0, 0.04, 0.09] plt.figure(figsize=(5,5)) # autopct='%.2f %%': %.2f display value upto 2 decimal, # %% is used for displaying % at the end plt.pie(x, explode=explode, labels=dataName, autopct='%.2f%%') plt.show() 

### Polar plot¶

In matplotlib, polar plots are based on clipping of the curve so that $rge0$. For example, in Fig. 2.7 (generated by line 12 in Listing 2.6), only two lobes of $$cos(2x)$$ are generated instead of four. Other two lobes have negative value of ‘r’, therefore these are clipped by the matplotlib. The actual four lobes are shown in Fig. 2.8, which can not be generated by matplotlib.

Polar plot, Fig. 2.7
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 #polarplotEx.py import numpy as np import matplotlib.pyplot as plt plt.close("all") x=np.linspace(0,2*np.pi, 1000) # polar axes is based on clipping so that r >= 0. # therefore only 2 lobes are shown as oppose to 4 lobes. y = np.cos(2*x) plt.polar(x, y) plt.show() 

### Bar chart¶

In this section, two types of bar charts are discussed. Listing 2.7 plots a simple bar chart for ‘years vs x’; whereas Listing 2.8 plots multiple data.

Bar Chart, Fig. 2.9
  1 2 3 4 5 6 7 8 9 10 11 #barchartEx.py import matplotlib.pyplot as plt plt.close("all") x = [1, 2, 4] years = [1999, 2014, 2030] plt.bar(years, x) plt.show() 
• Explanation Listing 2.8

In Fig. 2.10, the data ‘increment’ is plotted above the data ‘A’ using ‘bottom’ parameter in line 14.

Further, in the lower subplot, bar charts are plotted side by side using combination of ‘locs’ and ‘width’ variable in line 24 and 25. ‘width’ parameter set the width of the bar; which is set to 0.2 in line 24. Line 27 plots the data ‘x’ first; then, line 28 plots next data set i.e. ‘y’, but location is shifted by the ‘width’ due to command ‘locs+width’ in the line. Hence, bar chart is plotted beside the bars of the line 27. After that, line 29 shifted the plot of data ‘z’ by ‘2*width’. Finally line 32 add ticks for the x-axis and we get the final plot as shown in Fig. 2.10.

Bar Chart with multiple data, Fig. 2.10
  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 #barchartCombineEx.py import numpy as np import matplotlib.pyplot as plt plt.close("all") #### subplot 1 A = [2, 4, 8, 6] increment = [5, 6, 4, 1] years = [2005, 2010, 2015, 2020] plt.subplot(2,1,1) plt.bar(years, A, color = 'b', label='A') plt.bar(years, increment, color = 'r', bottom = A, label='increment') plt.legend() plt.show() ##### subplot 2 x = [1, 2, 4] y = [3.5, 3, 2] z = [2, 3, 1.5] width = 0.2 locs = np.arange(1, len(x)+1) plt.subplot(2,1,2) plt.bar(locs, x, width=width, label='x') plt.bar(locs+width, y, width=width, color="red", label='y') plt.bar(locs+2*width, z, width=width, color="black", label='z') plt.legend() plt.xticks([1.25, 2.25, 3.25], [r'$2000$', r'$2005$', r'$2010$']) plt.show() 

## Miscellaneous¶

### Annotation¶

Annotation can be used to make graph more readable as show in Fig. 3.1. Text is added to graph using ‘annotate()’ command with two different methods as shown in line 25 and 40 in Listing 3.1. Also, ‘text()’ command (at line 49) is used to add text to the figure.

Annotation, Fig. 3.1
  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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 #annotateEx.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(0, 2*np.pi, 100) sinx=np.sin(x) # calculate sin(x) plt.plot(x,sinx, label='sin') # legend ############ Legend #################### plt.legend(loc="best") #show legend #### Lable and Grid #################### plt.xlabel("Radian") # x label plt.ylabel("Amplitude") # y label ############# Annotate ###################### #1. # other arrow style # '-', '->', '-[', '<-', '<->', 'fancy', 'simple', 'wedge' #sin(pi/2)=1 plt.annotate(r'$sin(\frac{\pi}{2})=1$', fontsize=16, xy=(1.5, 1), xytext=(1 , 0.5), arrowprops=dict(arrowstyle="->"), ) # 2. #============================================================= # width: The width of the arrow in points # frac: The fraction of the arrow length occupied by the head # headwidth: The width of the base of the arrow head in points # shrink: Moves the tip and the base of the arrow some percent # away from the annotated point and text, #============================================================= #sin(3*pi/2)=-1 plt.annotate(r'$sin(\frac{3\pi}{2})=-1$', fontsize=18, xy=(4.5, -1), xytext=(1.5 , -0.5), arrowprops=dict(facecolor='red', shrink = 0.04, connectionstyle="arc3,rad=.2"), ) # 3. #################### Add text to plot ########### plt.text(5, 0.5, 'This is \nSine wave'); plt.show() #display the plot 

### Sharing Axis¶

Listing Listing 3.2, Listing 3.3 and Listing 3.4 create the instances of figure() and subplot() functions of matplotlib to generate various plots.

#### Common axis for two plots¶

Here x axis is common for two different plots. Further, in one plot log y-axis is used.

• Explanation Listing 3.2

Line 11 creates an instance ‘fig1’ of figure() function. Then subfig1 and subfig2 instances of ‘fig1’ are created in line 14 and 15. ‘twinx()’ command in line 18, shares the x-axis for both the plots.

Line 22-24 set the various parameter for subfig1; also note that ‘set_’ is used for x and y labels. Then line 27-28 plots the second figure. Finally line 30 displays both the plots as shown in Fig. 3.2

Sharing Axis, Fig. 3.2
  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 #shareaxisEx.py import numpy as np import matplotlib.pyplot as plt N=100 x=np.linspace(0.1,4, N) e1 = np.exp(x) e2 = np.exp(-x) # create an object 'fig1' of figure() fig1 = plt.figure() # create two instances of fig1 at location 1,1,1 subfig1 = fig1.add_subplot(1,1,1) subfig2 = fig1.add_subplot(1,1,1) # share the x-axis for both plot subfig2 = subfig1.twinx() # plot subfig1 # semilogy for log 'y' axis, for log x use semilogx subfig1.semilogy(x, e1) subfig1.set_ylabel("log scale: exp(x)") subfig1.set_xlabel("x-->") # plot subfig2 subfig2.plot(x, e2, 'r') subfig2.set_ylabel("simple scale: exp(-x)") plt.show() 

#### Sharing Axis-ticks¶

Here, same y-axis ticks (i.e. [-3, 2]) are used for two subplots as illustrated in Fig. 3.3 using Listing 3.3. In the listing, line 15 and 16 create two subplots. Further, line 15 contains ‘sharey’ parameter which sets ticks in the y-axis of subfig2 equal to subfig1.

Sharing Y Axis ticks, Fig. 3.3
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #subplotEx2.py import numpy as np import matplotlib.pyplot as plt N=100 x=np.arange(N) rn = np.random.randn(N) r = np.random.rand(N) # create an object 'fig1' of figure() fig1 = plt.figure() # create two instances of fig1 subfig1 = fig1.add_subplot(2,1,1) subfig2 = fig1.add_subplot(2,1,2, sharey = subfig1) #share y axis # plot figures subfig1.plot(x, rn) subfig2.plot(x, r) plt.show() 

### Add legend outside the plot¶

In Listing 3.4, legends are placed outside the figure as shown in Fig. 3.4. It can be quite useful, when we have large number of figures in a single plot. Note that, in line 12, instance of subplot is created directly; whereas in Fig. 3.3, subplot are created using instances of figure(), which require ‘add_subplot’ command as shown in line 14 and 15 there.

Legend outside the plot, Fig. 3.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 #legendPosEx.py import matplotlib.pyplot as plt import numpy as np # close all the figures, if open from previous commands plt.close('all') ur = np.random.rand(100) nr = np.random.randn(100) x=np.linspace(0,3, 100) ax = plt.subplot(1,1,1) ax.plot(x, label="Line") ax.plot(ur, label="Uniform random number") ax.plot(nr, label="Normal random number") ax.set_title("Legend outside the plot") # Plot position and shriking to create space for legends box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.2, box.width, box.height * 0.8]) # Add legend below the axis ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2) plt.show() `