Matplotlibguide Readthedocs Io en Latest
Matplotlibguide Readthedocs Io en Latest
Table of contents i
1 Basic plots 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Data generation with Numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Basic Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.1 First Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.2 Label, Legend and Grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.3 Line style and Marker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.4 Axis and Title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Multiple Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Mutliplots in same window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4.3 Mutliplots in different windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2 Plot types 13
2.1 Semilog Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Scatter plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.4 Pie chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5 Polar plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.6 Bar chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3 Miscellaneous 24
3.1 Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2 Sharing Axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.1 Common axis for two plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.2 Sharing Axis-ticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3 Add legend outside the plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
i
Chapter 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.
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,
6 # 1. linspace(a, b, total_points)
7 x = np.linspace(2, 8, 4)
8 print(x) # [ 2. 4. 6. 8.]
9
10 # 2. sin(x)
11 sinx = np.sin(x) # x is consider as radian
12 print(sinx) # [ 0.90929743 -0.7568025 -0.2794155 0.98935825]
13
14 # 3. cos(x)
15 cosx = np.cos(x)
16 print(cosx) #[-0.41614684 -0.65364362 0.96017029 -0.14550003]
17
1
1.3. Basic Plots
In this section, basic elements of the plot e.g. Title, axis names and grid etc. are discussed.
Here Listing 1.2 is modified as shown in Listing 1.3, to add labels, legend and grid to the plot.
2 PythonDSP
Chapter 1. Basic plots
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,
4 PythonDSP
Chapter 1. Basic plots
6 PythonDSP
Chapter 1. Basic plots
37 plt.show()
In this section various mutliplots are discussed e.g. plots on the same figure window and subplots etc.
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.
25 plt.show()
8 PythonDSP
Chapter 1. Basic plots
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.
21 plt.subplot(2,1,2)
22 plt.plot(x,cosx, 'o-g', label='cos')
23 plt.grid() # show grid
24 plt.legend() #show legend
25 plt.xlabel(r'$Radian$') # x label
26 plt.ylabel(r'$Amplitude$') # y label
27 ############ Legend ####################
28
33
34 plt.show()
‘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 #multiplotDifferentWindow.py
2 import numpy as np
3 import matplotlib.pyplot as plt
4
10 PythonDSP
Chapter 1. Basic plots
32 plt.show()
12 PythonDSP
Chapter 2
Plot types
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 𝑒𝑥 .
Listing 2.1: Linear plot (Fig. 2.1) vs Semilog plot (Fig. 2.2)
1 #semilogEx.py
2 import numpy as np
3 import matplotlib.pyplot as plt
4
8 x=np.linspace(0.01, 5, 100)
9 e=np.exp(x)
10
11 #linear plot
12 plt.plot(x,e)
13 plt.xlabel("x")
14 plt.ylabel("y=exp(x)")
15 plt.title("Linear Y axis")
16
17 #semilog plot
18 #log(exp(x))=x therefore straight line will be displayed
19 plt.figure()
20 plt.semilogy(x,e) #semilogy: semilog y-axis
21 plt.xlabel("x")
22 plt.ylabel("y=exp(x)")
23 plt.title("Log Y axis")
24
2.2 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
13
2.2. Histogram
14 PythonDSP
Chapter 2. Plot types
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.
5 plt.close("all")
6
7 ur = np.random.rand(10000)
8 nr = np.random.randn(10000)
9
10 plt.subplot(2,2,1)
11 plt.hist(ur)
12 plt.xlabel("Uniform Random Number, Default 10 Bin")
13
14 plt.subplot(2,2,2)
15 plt.hist(ur, 20) # display 20 bins
16 plt.xlabel("Uniform Random Number, 20 Bin")
17
18 plt.subplot(2,2,3)
19 plt.hist(nr)
20 plt.xlabel("Normal Random Number, Default 10 Bin")
21
22 plt.subplot(2,2,4)
23 plt.hist(nr, 20) # display 20 bins
24 plt.xlabel("Normal Random Number, 20 Bin")
25
26 plt.show()
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.
5 plt.close("all")
6
7 N=100
8 x = np.linspace(0, 2*np.pi, N)
9 noise = np.random.randn(N)
10 signal = 2*np.sin(x)
11
12 y = signal + noise
13 plt.plot(x, signal) # signal + noise
14 plt.scatter(x, y) #scatter plot
15
16 plt.figure()
17 y = signal + 0.2*noise # singal + 0.2*noise i.e. low noise
18 plt.plot(x, signal)
19 plt.scatter(x, y) #scatter plot
20
21 plt.show()
16 PythonDSP
Chapter 2. Plot types
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.
4 plt.close("all")
5
12 plt.show()
4 plt.close("all")
5
10 plt.figure(figsize=(5,5))
11 # autopct='%.2f %%': %.2f display value upto 2 decimal,
12 # %% is used for displaying % at the end
13 plt.pie(x, explode=explode, labels=dataName, autopct='%.2f %% ')
14 plt.show()
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 𝑐𝑜𝑠(2𝑥) 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.
5 plt.close("all")
6
7 x=np.linspace(0,2*np.pi, 1000)
8
18 PythonDSP
Chapter 2. Plot types
14 plt.show()
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.
4 plt.close("all")
5
6 x = [1, 2, 4]
7 years = [1999, 2014, 2030]
8
9 plt.bar(years, x)
10
11 plt.show()
20 PythonDSP
Chapter 2. Plot types
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.
5 plt.close("all")
6
7 #### subplot 1
8 A = [2, 4, 8, 6]
9 increment = [5, 6, 4, 1]
10 years = [2005, 2010, 2015, 2020]
11
12 plt.subplot(2,1,1)
13 plt.bar(years, A, color = 'b', label='A')
14 plt.bar(years, increment, color = 'r', bottom = A, label='increment')
15 plt.legend()
16
17 plt.show()
18
19 ##### subplot 2
20 x = [1, 2, 4]
21 y = [3.5, 3, 2]
22 z = [2, 3, 1.5]
23
24 width = 0.2
25 locs = np.arange(1, len(x)+1)
26 plt.subplot(2,1,2)
27 plt.bar(locs, x, width=width, label='x')
28 plt.bar(locs+width, y, width=width, color="red", label='y')
29 plt.bar(locs+2*width, z, width=width, color="black", label='z')
30 plt.legend()
31
35 plt.show()
22 PythonDSP
Chapter 2. Plot types
Miscellaneous
3.1 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.
31 # 2.
32 #=============================================================
33 # width: The width of the arrow in points
34 # frac: The fraction of the arrow length occupied by the head
35 # headwidth: The width of the base of the arrow head in points
(continues on next page)
24
Chapter 3. Miscellaneous
47 # 3.
48 #################### Add text to plot ###########
49 plt.text(5, 0.5, 'This is \nSine wave');
50
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.
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
5 N=100
6 x=np.linspace(0.1,4, N)
7 e1 = np.exp(x)
8 e2 = np.exp(-x)
9
20 # plot subfig1
21 # semilogy for log 'y' axis, for log x use semilogx
22 subfig1.semilogy(x, e1)
23 subfig1.set_ylabel("log scale: exp(x)")
24 subfig1.set_xlabel("x-->")
25
26 # plot subfig2
27 subfig2.plot(x, e2, 'r')
28 subfig2.set_ylabel("simple scale: exp(-x)")
29
30 plt.show()
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.
5 N=100
6 x=np.arange(N)
7 rn = np.random.randn(N)
8 r = np.random.rand(N)
9
26 PythonDSP
Chapter 3. Miscellaneous
17 # plot figures
18 subfig1.plot(x, rn)
19 subfig2.plot(x, r)
20 plt.show()
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.
8 ur = np.random.rand(100)
9 nr = np.random.randn(100)
10 x=np.linspace(0,3, 100)
11
14 ax.plot(x, label="Line")
15 ax.plot(ur, label="Uniform random number")
16 ax.plot(nr, label="Normal random number")
17 ax.set_title("Legend outside the plot")
18
28 plt.show()
28 PythonDSP
Chapter 3. Miscellaneous