Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

Time:2021-9-6

Matplotlib is a python drawing library based on numpy. It is a tool for data visualization in machine learning.

We talked about it in the previous articleUsage of numpy, we won’t discuss the relevant knowledge of numpy here.
Matplotlib has strong tool properties, that is, it is only for my use. We don’t have to spend too much energy on it. We just need to know what it can do, what graphics it can draw, and an impression is enough. We take what we use in actual use. When we use it, we will naturally be proficient. The functions we can’t use show that it is of little use to you.
This is it.Learn on demand。 That’s what I’m talking aboutHow to be a tenfold programmerSimilar ideas have been mentioned in.

1、 Common usage of Matplotlib

1. Draw simple images

We use the most common activation function in machine learningsigmoidFor example, let’s draw 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)
plt.show()

The formula of sigmoid is: $y = f (x) = \ frac {1} {1 + e ^ {- x}}$
The plot () method shows the trend between variables, and the show () method shows the image.
We get the image as shown in the figure:
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

2. Add common elements

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

x = np.linspace(-10,10,1000)

#Write 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 labeling
plt.xlabel("X axis")

#Y-axis labeling
plt.ylabel("Y axis")

#Title
plt.title("sigmoid function")

#Set the grid, red dotted line on the way
plt.grid(linestyle=":", color ="red")

#Set horizontal guides
plt.axhline(y=0.5, color="green", linestyle="--", linewidth=2)

#Set vertical guides
plt.axvline(x=0.0, color="green", linestyle="--", linewidth=2)

#Draw curve
plt.plot(x,y)

#Save image
plt.savefig("./sigmoid.png",format='png', dpi=300)

The above code includes limiting the range of X and Y axes, adding titles and labels, setting grids, adding reference lines, saving images, etc.
Draw the image as follows:

Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

3. Draw multi curve

#Generate 1000 evenly distributed values
x = np.linspace(-10,10,1000)

#Write sigmoid formula
y = 1 / (1 + np.exp(-x))
z = x**2
plt.xlim(-2,2)
plt.ylim(0,1)

#Draw sigmoid
plt.plot(x,y,color='#E0BF1D',linestyle='-', label ="sigmoid")

#Draw y = x * x
plt.plot(x,z,color='purple',linestyle='-.', label = "y=x*x")

#Draw legend, which is the legend in the corner of the figure below
plt.legend(loc="upper left")

#Display
plt.show()

You can draw multiple images by directly calling multiple plot(). Note: if you do not call the legend () method, the legend in the upper left corner will not be drawn. amongcolorThe parameter supports hex representation.
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

4. Recognize figure (canvas)

First, we know figure (canvas), such as legend, which we mentioned above, is the display of line labels. The dotted line enclosed by the grid is the grid reference line. Title / X axislabel and other text labels.
This figure helps us to understand the values of figure.

Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

5. Draw multiple images

A figure can correspond to multiple plots. Now we try to draw multiple images on one figure.

x = np.linspace(-2*np.pi, 2*np.pi, 400)
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)

#Create a sub image with two rows and two columns
fig, ax_list = plt.subplots(nrows=2, ncols=2)

#'R -' where R represents color = red and - represents linestyle = '-'
ax_list[0][0].plot(x,y,'r-')
ax_list[0][0].title.set_text('sin')

ax_list[0][1].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')

ax_list[1][1].plot(x,z,'g')
ax_list[1][1].title.set_text('sigmoid')

#Adjust the layout of sub images
fig.subplots_adjust(wspace=0.9,hspace=0.5)
fig.suptitle("Figure graphs",fontsize=16)

Among them, the most critical issubplotsMethod to generate a sub image of 2 rows and 2 columns, and then we call ax_ List.
among'r-''b-.'The parameter is the abbreviation of the drawing, which will be explained separately in the subsequent parameter abbreviation paragraphs of this article.

Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

6. Draw common drawings

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

#Make drawing support Chinese
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
#Create a sub image with two rows and two columns
fig, [[ax1,ax2],[ax3,ax4],[ax5,ax6]] = plt.subplots(nrows=3, ncols=2,figsize=(8,8))

#Draw histogram bar
value = (2, 3, 4, 1, 2)
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 ')

#Draw histogram
h = 100 + 15 * np.random.randn(437)
ax2.hist(h, bins=50)
ax2.title.set_ Text ('histogram ')

#Draw pie chart pie
labels = 'Frogs', 'Cai', 'Yongji', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
ax3.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax3.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
ax3.title.set_ Text ('pie chart ')

#Drawing cotton stick
x = np.linspace(0.5, 2*np.pi, 20)
y = np.random.randn(20)
ax4.stem(x,y, linefmt="-.", markerfmt="o", basefmt='-')
ax4.set_ Title ("cotton swab chart")

#Bubble chart scatter
a = np.random.randn(100)
b = np.random.randn(100)
ax5.scatter(a, b, s=np.power(2*a+4*b,2), c=np.random.rand(100), cmap=plt.cm.RdYlBu, marker="o")

#Draw polar graph
fig.delaxes(ax6)

ax6 = fig.add_subplot(236, projection='polar')
#ax6 = fig.add_ Subplot (2,3,6, projection ='polar ') #2 row, 3 columns, 6th figure
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])  # Less radial ticks
ax6.set_rlabel_position(-22.5)  # Move radial labels away from plotted line
ax6.grid(True)

#Adjust the layout of sub images
fig.subplots_adjust(wspace=1,hspace=1.2)
Fig. subtitle ("graphic drawing", fontsize = 16)

Draw the image as follows:
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

7. Parameter abbreviation

Because Matplotlib supports parameter abbreviations, I think it is necessary to talk about the representation of parameter abbreviations separately.

x = np.linspace(-10,10,20)
y = 1 / (1 + np.exp(-x))
plt.plot(x,y,c='k',ls='-',lw=5, label ="sigmoid", marker="o", ms=15, mfc='r')
plt.legend()

Draw the image as follows:
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

7.1 C stands for color

character colour
‘b’ blue
‘g’ green
‘r’ red
‘c’ cyan
‘m’ magenta
‘y’ yellow
‘k’ black
‘w’ white

7.2 LS stands for linestyle

character describe
‘-‘ solid line style
‘–‘ dashed line style
‘-.’ dash-dot line style
‘:’ dotted line style
‘.’ point marker
‘,’ pixel marker
‘o’ circle marker
‘v’ triangle_down marker
‘^’ 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
‘*’ 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 (mark style)

The mark style is shown as follows:
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

7.4 other abbreviations

  1. lwRepresents line width, for example: LW = 2.5
  2. msRepresents marker size, such as Ms = 5
  3. mfcRepresents marker color, such as MFC =’Red ‘

2、 Advanced usage of Matplotlib

1. Add text notes

We can add text, arrows and other annotations on the canvas to make the image more clear and accurate.
We callannotateMethod to draw the annotation.

fig, ax = plt.subplots(figsize=(8, 8))

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)

#Draw a curve
line, = ax.plot(t, s)

#Add comments
ax.annotate('figure pixels',
            xy=(10, 10), xycoords='figure pixels')
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)

#First arrow
ax.annotate('point offset from data',
            xy=(2, 1), xycoords='data',
            xytext=(-15, 25), textcoords='offset points',
            arrowprops=dict(facecolor='black', shrink=0.05),
            horizontalalignment='right', verticalalignment='bottom')

#Second arrow
ax.annotate('axes fraction',
            xy=(3, 1), 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))

Draw the image as follows:

Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

2. Draw 3D image

Drawing 3D images requires importingAxes3DLibrary.

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 = np.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 colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

amongcmapIt means colormap, which is used to draw color distribution, gradient, etc.cmapUsually cooperatecolorbarUse to draw the color bar of the image.

Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

3. Import image (California house price)

introducempimgLibrary to import images.
Taking the California house price data of the United States as an example, we import the California house price data to draw a scatter chart, and import the California map pictures to view the data of house prices corresponding to the longitude and latitude of the map. At the same time, use the color bar to draw the 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 house price data (we don't care about domain names)
housing = pd.read_csv("http://blog.caiyongji.com/assets/housing.csv")
#California map
url = "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("./", "california.png"))

#Plot house price scatter chart according to longitude and latitude
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, alpha=0.4,
                      )
plt.imshow(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", fontsize=14)

prices = housing["median_house_value"]
tick_values = np.linspace(prices.min(), prices.max(), 11)

#Color bar, heat map
cbar = plt.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)

Draw the image as follows:
Red is expensive and blue is cheap. The size of the circle indicates the population
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

4. Draw contour lines

Contour lines are useful for drawing 3D images in 2D 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()

Draw the image as follows:
The black place is the peak and the red place is the valley.

Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

Draw animation

Animation needs to be introducedanimationLibrary, by callingFuncAnimationMethod 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.plot([], [], lw=2)

#Initialization method
def init():
    line.set_data([], [])
    return line,

#Data update method, called periodically
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,

#Draw animation, frame number, interval cycle line, call the animate method
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)
anim.save('ccccc.gif', fps=30)

plt.show()

In the above codeanim.save()Method supports saving MP4 format files.
The dynamic diagram is drawn as follows:
Pre machine learning (V): master the common usage of Matplotlib in 30 minutes

epilogue

So far, the pre machine learning series is over. We have made full preparations for learning on mobile phones. View completeAdvanced machine learning seriesPlease pay attention to the official account number (caiyongji) or visit my personal blog.blog.caiyongji.comSynchronize updates.
You may find that my tutorial is more practical. The next series of machine learning tutorials will also be more practical than theoretical.

Students who are afraid of mathematics don’t panic. Just follow me slowly.