Matplotlib is a Python drawing library built on top of NumPy. It is a tool for data visualization in machine learning.

We have covered the use of NumPy in previous articles, so we will not discuss NumPy here. Matplotlib has a very strong tool nature, which means it’s just for me and we don’t have to work too hard to refine it. We just need to know what it can do, what it can draw, and get an impression. What we use in practice is what we get. When we use it naturally, we become proficient. When we do not use it, it means that it is not useful to you. That’s learning on Demand. This is a similar idea I discussed in How to Be a 10x Programmer.

Matplotlib = Matplotlib

1. Draw simple images

Let’s take sigmoid, the most common activation function in machine learning, for example, and plot it.

Import matplotlib.pyplot as PLT import numpy as NP x = np.linspace(-10,10,1000) y = 1 / (1 + np.exp(-x)) plt.plot(x,y) import matplotlib.pyplot as PLT import numpy as NP x = np.linspace(-10,10,1000) y = 1 / (1 + np.exp(-x)) plt.plot(x,y) plt.show()Copy the code

The formula of sigmoid is:
y = f ( x ) = 1 1 + e x y = f(x) =\frac{1}{1+e^{-x}}
The plot() method shows the trend between variables, and the show() method shows the graph.

We get the following image:

2. Add common elements

We added some reference elements, and I annotated each function in detail in the code.

X = np.linspace(-10,10,1000) # write the formula y = 1 / (1 + Np.exp (-x)) # X-axis range limit plt.xlim(-5,5) # Y-axis range limit plt.ylim(-0.2,1.2) # X-axis add tag Plt. ylabel(" y Axis ") # title plt.title("sigmoid function") # Set grid, Axhline (y=0.5, color="green", linestyle="--", Linestyle ="--", linestyle="--", Savefig ("./sigmoid.png",format=' PNG ', dpi=300)Copy the code

The above code includes limiting X and Y ranges, adding titles and labels, setting up grids, adding guides, and saving images. Draw the image as follows:

3. Draw multiple curves

Y = 1 / (1 + np.exp(-x)) z = x**2 plt.xlim(-2,2) plt.ylim(0,1) Sigmoid plt.plot(x,y,color='#E0BF1D',linestyle='-', Plot (x,z,color='purple',linestyle='-.', label =" y=x*x") # plot(x,z,color='purple',linestyle='-.', label =" y=x*x") # plot Plt.legend (loc="upper left") # show plt.show()Copy the code

To draw multiple plots, call multiple plots () directly. Note: Legend in the upper left corner is not drawn if the legend() method is not called. Among themcolorThe parameter can be hex.

4. Figure out the canvas

First of all, we know figure(canvas), such as Legend as we mentioned above, which is the display of line labels. The dotted lines circled by the grid are the grid guides. Text labels such as Title/ X AxisLabel. This diagram helps us to get a value view of figure.

5. Draw multiple images

A figure can correspond to multiple plots. Now let’s try to draw multiple images on a figure.

x = np.linspace(-2*np.pi, 2*np.pi, 100) y = np.sin(x**2) z = 1 / (1 + np.exp(-x)) a = np.random. Randint (0,100,400) b = np.maximum(x,0.1*x) Ax_plots (nrows=2, ncols=2) # 'r-') = '-' - said graphics.linestyle ax_list [0] [0]. The plot (x, y, 'r -) ax_list [0] [0]. Title. Set_text (' sin') ax_list [0] [1]. The scatter (x, a, s = 1) ax_list[0][1].title.set_text('scatter') ax_list[1][0].plot(x,b,'b-.') ax_list[1][0].title.set_text('leaky relu') Plot (x,z,'g') ax_list[1][1].tit.set_text ('sigmoid') # Adjust subplots_adjust(wspace=0.9,hspace=0.5)  fig.suptitle("Figure graphs",fontsize=16)Copy the code

The key of the plots is the subplots method, which generates two rows and two columns of subplots and then calls each plotting method in ax_list. Among them, ‘r-‘ and ‘b-.’ parameters are abbreviations of drawing, which will be explained separately in the subsequent paragraphs of this paper.

6. Draw common diagrams

We often use graphs to represent the relationship between data, including histogram, bar chart, pie chart, scatter chart and so on.

Plt.rcparams ['font. Sans-serif ']=['Microsoft YaHei'] [[ax1, ax4],[ax5,ax6]] = copy-plot (nrows=3, ncols=2,figsize=(8,8)) Index = np.arange(5) ax1.bar(index, value,alpha=0.4, Color ='b') ax1.set_xlabel('Group') ax1.set_ylabel('Scores') ax1.set_title(' histogram ' Hist (h, bins=50) ax2.title. Set_text (' bar ') # = = 'Frogs'; 'Logs' sizes = [15, 30, 45, 10] explode= (0, 0.1, 0, 0) ax3.pie(sizes, explode=explode, labels=labels, Autopct = '% % % 1.1 f, shadow = True, Axis ('equal') # Equal aspect ratio ensures that pie is drawn as a circes.ax3.title.set_text (' pie chart ') Stem x = np.linspace(0.5, 2* Np.pi, 20) y = NP.random. Randn (20) ax4.stem(x,y, linefmt="-.", markerfmt="o", A = np.random. Randn (100) b = NP.random. Randn (100) ax5. s=np.power(2*a+4*b,2), c=np.random.rand(100), cmap=plt.cm.RdYlBu, Add_subplot (236, projection='polar') #ax6 = add_subplot(2,3,6) Projection ='polar')#2 rows, 3 columns, R = np.arange(0, 2, 0.01) theta = 2 * np. PI * r ax6.plot(theta, r) ax6.set_rmax(2) ax6.set_rticks([0.5, 1, 1.5, 2]) # convert ax6.0.0.0 to convert ax6.0.0.0 into convert ax6.0.0.0 # Adjust subplots_adjust(wspace=1,hspace=1.2) fig.Suptitle (" draw ", fontSize =16)Copy the code

Draw the image as follows:

7. Parameter shorthand

Since Matplotlib supports parameter abbreviations, I thought it would be worth taking a separate look at the representation of parameter abbreviations.

X = np. Linspace (5-10,10,20) y = 1 / (1 + np. Exp (x)) PLT. The plot (x, y, c = 'k', ls = '-', lw = 5, label = "sigmoid", marker = "o", ms=15, mfc='r') plt.legend()Copy the code

Draw the image as follows:

7.1 C stands for color

character color
“B” blue
‘g’ green
“R” red
“C” cyan
‘m’ magenta
‘y’ yellow
“K” black
“W” white

7.2 LS stands for Linestyle

character describe
The ‘-‘ solid line style
The ‘-‘ dashed line style
‘-‘ dash-dot line style
‘:’ dotted line style
‘. ‘ point marker
‘, ‘ pixel marker
‘o’ circle marker
‘v’ triangle_down marker
A ‘^’ triangle_up marker
‘<‘ triangle_left marker
‘>’ triangle_right marker
‘1’ tri_down marker
‘2’ tri_up marker
‘3’ tri_left marker
‘4’ tri_right marker
‘s’ square marker
‘p’ pentagon marker
The ‘*’ star marker
‘h’ hexagon1 marker
‘H’ hexagon2 marker
‘+’ plus marker
‘x’ x marker
‘D’ diamond marker
‘d’ thin_diamond marker
‘|’ vline marker
‘_’ hline marker

7.3 Marker (Marker Style)

The token style is shown as follows:

7.4 Other Abbreviations

  1. lwRepresents lineWidth, for example, lw=2.5
  2. msRepresents markersize, e.g. Ms =5
  3. mfcStands for MarkerFacecolor (marker color), e.g. MFC =’red’

2, Matplotlib advanced usage

1. Add text comments

We can add text, arrows and other annotations on the canvas (figure) to make the image more clear and accurate. We draw the annotation by calling the Annotate method.

Arange (0.0, 5.0, 0.01) s = np.cos(2*np. PI *t) # plot(t, bplots), = ax.plot(t, bplots) Ax. annotate('figure points', xy=(80, 80), xycoords='figure points') ax.annotate('figure fraction', xy=(.025, .975), xycoords='figure fraction', Horizontalalignment ='left', verticalalignment='top', fontsize=20) # ax.annotate('point offset from data', xy=(2, 1), xyCoords ='data', xytext=(-15, 25), textCoords ='offset points', arrowprops=dict(facecolor='black', shrink=0.05), Axis alignment='right', verticalalignment='bottom') # axes alignment='right', verticalalignment='bottom' Xycoords ='data', xytext=(0.8, 0.95), TextCoords ='axes fraction', Arrowprops =dict(facecolor='black', shrink=0.05), horizontalalignment='right', verticalalignment='top') ax.set(xlim=(-1, 5), ylim=(-3, 5))Copy the code

Draw the image as follows:

2. Draw 3D images

Drawing 3D images requires importing the Axes3D library.

from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker  import LinearLocator, FormatStrFormatter import numpy as np FIG = plt.figure(figsize=(15,15)) ax = FIG. Gca (projection='3d') # Make data.x = Arange (-5, 5, 0.25) Y = np. Arange (-5, 5, 0.25) X, Y = np. Meshgrid (X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, Linewidth =0, antialiased=False) # Customize the z axis.ax.set_zlim (-1.01, 1.01) Ax.zaxis. Set_major_locator (LinearLocator(10)) Ax.zaxis. Set_major_formatter (FormatStrFormatter('%.02f')) # Add a Color bar which maps values to color.fig. Colorbar (surf, shrink=0.5, aspect=5)Copy the code

Cmap stands for colorMap, which is used to draw color distribution and gradient color. Cmap is usually used in conjunction with colorbar to draw the colorbar of the image.

3. Import images (California housing prices)

Import the MPIMG library to import images. Taking the housing price data of California as an example, we import the housing price data of California to draw the scatter chart, and import the map picture of California to check the data corresponding to the longitude and latitude of the map. Also using the color bar, draw a heat image. The code is as follows:

import os import urllib import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.image As mpimg # California prices data (you don't have to care about domain name) housing = pd. Read_csv (" http://blog.caiyongji.com/assets/housing.csv ") url = # California map "http://blog.caiyongji.com/assets/california.png" urllib.request.urlretrieve("http://blog.caiyongji.com/assets/california.png", os.path.join("./", "california.png")) california_img=mpimg.imread(os.path.join("./", Ax = housing. Plot (kind="scatter", x="longitude", y="latitude", figsize=(10,7), s=housing['population']/100, label="Population", c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=False, California_img, extent=[-124.55, -113.80, 32.45, 42.05], alpha=0.5, cmap=plt.get_cmap("jet")) plt.ylabel("Latitude", fontsize=14) plt.xlabel("Longitude", Linspace (prices.min(), prices.max(), 11) # Colorbar (ticks=tick_values/prices.max()) cbar.ax.set_ytickLabels (["$%dk"%(round(v/1000))) for v in tick_values], fontsize=14) cbar.set_label('Median House Value', fontsize=16) v plt.legend(fontsize=16)Copy the code

Draw the image as follows:

Red is expensive, blue is cheap, and the size of the circle is population

4. Draw contour lines

Contour lines are useful for drawing three-dimensional images in two-dimensional space.

def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar()
Copy the code

Draw the image as follows: peaks in black and valleys in red.

Draw the animation

Animation library is introduced to draw animation, and FuncAnimation method is called to draw animation.

import numpy as np from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure() ax = PLT. Axes (xlim = (0, 2), ylim = (2, 2)) line, = ax. The plot ([], [], lw = 2) # initialization method def init () : Line.set_data ([], []) return line, def animate(I): X = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * I)) line.set_data(x, y) return line, Anim = animation.FuncAnimation(FIG, animate, init_func=init, frames=200, interval=20, blit=True) anim.save('ccccc.gif', fps=30) plt.show()Copy the code

In the code aboveanim.save()Method supports saving mp4 files.

Draw the GIF as follows:

conclusion

This concludes our front-loading machine learning series, and we’re ready for hands-on machine learning. For the full series on front-loading machine learning, please visit caiyongji or my blog at blog.caiyongji.com. As you may have noticed, my tutorial is more hands-on. The next series of machine learning tutorials will also be more practical than theoretical.

Don’t panic if you are afraid of math, just follow me and learn it slowly.