Matplotlib is a drawing library for Python. It can be used with NumPy, and Matplotlib is also a common drawing library for deep learning. It is mainly used to graph the results of training, because it is more intuitive and easier to find problems in training.

This article is shared from huawei cloud community “deep learning basis of Matplotlib, one article to fix each example, suggest collection after reference to the various AI show”, author: cilantro chat game.

Matplotlib is a drawing library for Python. It can be used with NumPy, and Matplotlib is also a common drawing library for deep learning. It is mainly used to graph the results of training, because it is more intuitive and easier to find problems in training.

1. Let’s do a demo analysis

The following is a typical graph. If we want to develop such a graph, what should we do? What data should we prepare?

1. How to make a picture? How do I create an artboard?

2. How to set the data? How do I put the x and y data up there

3. Set the map marking. How to draw the small form with the colors of the lines in the upper left corner?

4. Appearance, how to deal with the different colors of different lines?

5, how to display?

6. How to keep it?

So many questions, what’s wrong? Step by step, let me show you the code first, see how much I can understand

x = np.linspace(0, 2, 100)

plt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic')  # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
Copy the code

2. Concepts in Matplotlib

Here’s an image from the official website that points to a number of concepts, most of which we can see and seem to understand

Figure (container)

The entire image is called Figure, which is used to hold the returned Axes(coordinate field). A Figure can contain any number of Axes and can be understood as a container.

Axes(coordinates)

You can think of it as a single artboard, A Axes contains two Axes (three in 3D), each Axes has a title(method :set_title()), an X-label (method :set_xlabel()), A y-label(method :set_ylabel()). Note: A given Axes object can only be included in one Figure.

Axis

It’s kind of like a number line. You can use Axis and Axis methods to set the style of the scale on the Axis and the value on the Axis. The location of the scale is determined by the Locater object and the corresponding value of the scale is determined by the Formatter object.

Summary: Axes is pretty much what we think of as a ‘plot’. Sheet paper, so to speak. A defined figure can have many Axes, but a defined Axes can only be in one figure.

Axes of 2-dimensional space contains two Axes (x and Y) and Axes of 3-dimensional space contains three Axes (x, y, and Z). Note here the distinction between Axes and Axis.

Axis is a number line object that is used to set the data constraints of a Axes (the values of the two endpoints) and the ticks and tick-labels labels on the Axes.

Subplot: One or more Subplot objects (axes) are created under the figure object to plot the image.

Axes: Sets the color of the boundary and surface of the axes, the size of the coordinate scale values and the display of the grid

Figure: Controls DPI, boundary color, graph size, and subplot Settings

Grid: Sets the color and linearity of the grid

Legend: Sets the display of the legend and the text in it. Line: Sets the lines (color, line, width, etc.) and markers

Patch: Is a graphical object that fills a 2D space, such as polygons and circles. Control line width, color, anti-aliasing Settings, etc.

Savefig: You can set the saved graph separately. For example, set the background of the rendered file to white.

Verbose: Sets matplotlib information output during execution, such as silent, HELPFUL, debug, and Debug-annoying.

Xticks and yticks: Sets the color, size, orientation, and label size for the primary and secondary ticks on the X and y axes.

3. Graphics supported by Matplotlib

Chart 3.1 line

Import matplotlib.pyplot as PLT import numpy as np # Data for plotting t = np.arange(0.0, 2.0, n = n) 0.01) s = 1 + np. Sin (np. 2 * PI * t), FIG, ax = PLT, subplots (ax). The plot (t, s) ax. Set (xlabel = 'time (s) ", ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() fig.savefig("test.png") plt.show()Copy the code

3.2 Histogram HIST

import numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) # example data mu = 100 # mean of distribution sigma = 15 # standard deviation of distribution x = mu + sigma * np.random.randn(437) num_bins = 50 fig, ax = plt.subplots() # the histogram of the data n, bins, patches = ax.hist(x, num_bins, Density =True) # add a 'best fit' line y= ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins -) mu))**2)) ax.plot(bins, y, '--') ax.set_xlabel('Smarts') ax.set_ylabel('Probability density') ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') # Tweak spacing to prevent clipping of ylabel fig.tight_layout() plt.show()Copy the code

3.3 the route

import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, Ax = plt. plots() Path = mpath.Path path_data = [(path.moveto, (1.58, -2.57)), (path.curve4, (0.35, -1.1)), (Path. CURVE4, (1.75, 2.0)), (Path. CURVE4 (0.375, 2.0)), (Path. LINETO (0.85, 1.15)), (Path. CURVE4 (2.2, 3.2)), (Path. CURVE4, (3, 0.05)), (Path. CURVE4 (2.0, 0.5)), (Path. CLOSEPOLY (1.58, 2.57)), codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', Plot control points and connecting lines x, y = zip(*path.vertices) line, = max.vertices (x, 0) y, 'go-') ax.grid() ax.axis('equal') plt.show()Copy the code

3.4 Scatter

3.5 Polar plots

Import numpy as np import matplotlib.pyplot as PLT r = np.arange(0, 2, 0.01) theta = 2 * np. PI * r FIG, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.plot(theta, r) ax.set_rmax(2) ax.set_rticks([0.5, 1, 1.5, 2]) # convert ax.set_rlabel_position(-22.5) # convert convert away from ax.grid(True) ax.set_title("A line plot on a polar axis", va='bottom') plt.show()Copy the code

3.6 pie pie

import matplotlib.pyplot as plt # Pie chart, where the slices will be ordered and plotted counter-clockwise: Labels = 'Frogs', 'Frogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0, 0); 0) # only "explode" the 2nd slice (i.e. 'Hogs') fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, Labels = labels, autopct = '% % % 1.1 f, shadow = True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()Copy the code

3.7 3 d graphics

import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np  fig, ax = plt.subplots(subplot_kw={"projection": X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.arange(-5, 5, 0.25) X, 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)) # A StrMethodFormatter is used automatically Ax.zaxis. Set_major_formatter ('{x:.02f}') # Add a colorbar which maps values to color.fig. Colorbar (surf, shrink=0.5, shrink=0.5, aspect=5) plt.show()Copy the code

X =np.arange(-5,5,0.1) y=x*3 Figure (num=1, figsize=(15, 8),dpi=80) Number of rows, number of columns, number of rows. Ax2 = FIG. Add_subplot (2,1,2) Print (FIG,ax1,ax2) print(FIG,ax1,ax2) Axarr,axarr,axarr,axarr,axarr,axarr,axarr,axarr,axarr,axarr Create a window and a subgraph at once. Ax1 = plt.subplot(1,1,1,facecolor='white') Print (ax1) # print(ax1) # FIG. Subplots_adjust (left=0) # Set the left margin of the window to 0, i.e. the left margin to 0. Ax1.set_title ('python-drawing') Plt.title ax1.set_xlabel('x-name') # set x axis name,plt.xlabel ax1.set_ylabel('y-name') # set y axis name,plt.ylabel Plt. axis([-6,6,-10,10]) # set the horizontal and vertical axis range, which is decomposed into the following two functions in the subgraph ax1.set_xlim(-5,5) # set the horizontal axis range, Plt.xlim ax1.set_ylim(-10,10) # set the vertical range, Plt. ylim xmajorLocator = MultipleLocator(2) # defines the scale difference of the horizontal primary label as a multiple of 2. MultipleLocator(3) ymajorLocator = MultipleLocator(3) Ax1.xaxism.set_major_locator (xmajorLocator) #x axis application defines horizontal master scale format. If not, the default scale format ax1.yaxism.set_major_locator (ymajorLocator) #y axis is defined by the vertical main scale format. Grid (True, which='major') #x axis grid uses the defined primary scale format ax1.yaxi.grid (True, which='major') Set_xticks ([]) # Remove the ticks ax1.set_xticks((-5,-3,-1,1,3,5)) # Set the ticks Set_xticklabels (labels=['x1','x2','x3','x4','x5'],rotation=-30,fontsize='small') Plot1 =ax1.plot(x,y,marker='o',color='g',label='legend1') Marker plot2=ax1.plot(x,y,linestyle='--',alpha=0.5,color='r',label='legend2') Linestyle linear, alpha transparency, color, Plt.legend () ax1.text(2.8, 7, R 'y=3*x') # annotate('important point', xy=(2, 6), xytext=(3, 1.5), Comment text, points, text positions, arrow properties arrowprops=dict(facecolor='black', shrink=0.05),) # display the grid. The which parameter has values of major(large scale only), minor(small scale only), both, and the default is major. Grid (b=True,which='major',axis='both',alpha= 0.5,color='skyblue', Linestyle ='--', lineWidth =2) Axes = plT.axes ([.2,.3,.1,.1], facecolor='y') # add a subgraph to the current window, rect=[left, bottom, width, height], is the absolute layout used, Plt. savefig('aa.jpg',dpi=400,bbox_inches='tight') # Save images, dPI resolution, Plt.show () # open the window and draw it in the window for method 1. For method 2 and method 3, if the coordinate system is blank, do not draw itCopy the code

conclusion

Most of the data above is summarized from the official website,

Matplotlib.org/stable/tuto…

If the above is not accurate, you can refer to the official website. I can only draw simple pictures to meet daily needs

Click to follow, the first time to learn about Huawei cloud fresh technology ~