@TOC
Introduction to Pyplot
-
Pyplot is a sublibrary of Matplotlib that provides a plotting API similar to MATLAB.
-
Pyplot is a common plotting module that makes it easy for users to plot 2D charts.
-
Pyplot contains a series of functions related to plot functions, each of which makes some changes to the current image, such as labeling the image, generating a new image, generating a new plot area within the image, and so on.
Import Pyplot
We can import the Pyplot library using import and set an alias PLT:
from matplotlib import pyplot as plt
Copy the code
This allows us to reference the pyplot package methods using PLT.
Plot
✈️1. Line chart
from matplotlib import pyplot as plt
import numpy as np
xpoints=np.array([0.10])
ypoints=np.array([0.100])
plt.plot(xpoints,ypoints)
plt.show()
Copy the code
We draw a line chart with two points (0,0) and (10,100). The X-axis coordinates are 0 and 10, and the Y-axis coordinates are 0,100. Place the X-axis and Y-axis points in the array respectively, then call plot to draw on the canvas, and finally show will be displayed. 🚄2. Be familiar with plot() functions
Plot () it plots points and lines in the following syntax:
# Draw a single line
plot([x], y, [fmt], *, data=None, **kwargs)
# Draw multiple linesplot([x], y, [fmt], [x2], y2, [fmt2], ... , **kwargs)Copy the code
- X, Y: nodes of points or lines. X is the X-axis data and y is the Y-axis data. The data can be tabled or array.
- FMT: Optional, defines basic formats such as colors, marks, and line styles.
- **kwargs: Optional, used on 2d planar graphs to set specified properties such as labels, line widths, etc.
Color characters: ‘B’ blue, ‘M’ magenta, ‘G’ green, ‘Y’ yellow, ‘R’ red, ‘K’ black, ‘W’ white, ‘C’ turquoise, ‘#008000’ RGB color string. If no color is specified for multiple curves, different colors are automatically selected.
Line styles :’ ‐’ solid, ‘‐‐’ broken, ‘‐.’ dotted, ‘:’ dashed.
Mark characters: ‘.’ dot mark,’,’ pixel mark (minimum point),’ O ‘solid circle mark,’ V’ inverted triangle mark,’ ^’ upper triangle mark,’ >’ right triangle mark,’ <‘ left triangle mark, etc.
Paper come zhongjue shallow, must know this to practice, we see the following examples will understand.
We can plot as many points as we want, just make sure we have the same number of points on both axes. Draw an irregular line with coordinates of (1, 3), (2, 8), (6, 1), (8, 10), corresponding to two arrays: [1, 2, 6, 8] and [3, 8, 1, 10].We make the lines red and dotted, and mark each point with an ‘O’ symbol:
from matplotlib import pyplot as plt
import numpy as np
xpoints=np.array([1.2.6.8])
ypoints=np.array([3.8.1.10])
plt.plot(xpoints,ypoints,'r--o')
plt.show()
Copy the code
You can see that there is an extra parameter in plot'r--o'
In fact, it is just [FMT], respectively represents the color character R, line style –, mark character O, the order of these three, arbitrary number, very convenient.Here the parameter is changed'.g-.'
, you can see that the first argument in the quotation marks is the symbol ‘. ‘; The second is the color character G; The third is line style -. So it becomes a green dotted line, and the dots are marked.
plt.plot(xpoints,ypoints,'.g-.')
Copy the code
If we do not specify a point on the X-axis, x will be set to 0, 1, 2, 3 depending on the value of y.. N – 1.
from matplotlib import pyplot as plt
import numpy as np
ypoints=np.array([2.6.2.6.2])
plt.plot(ypoints,'.c:')
plt.show()
Copy the code
You can see from the figure below that the default value of x is set to [0, 1, 2, 3, 4]. 🚉 3. Axis labels and headings
We can use the xlabel() and yLabel () methods to set the labels for the x and y axes.
from matplotlib import pyplot as plt
import numpy as np
xpoints=np.array([1.2.3.4.5])
ypoints=np.array([5.3.8.5.9])
plt.plot(ypoints,'oc-')
plt.xlabel('x-label')
plt.ylabel('y-label')
plt.show()
Copy the code
We can use the title() method to set the title.
from matplotlib import pyplot as plt
import numpy as np
xpoints=np.array([1.2.3.4.5])
ypoints=np.array([5.3.8.5.9])
plt.plot(ypoints,'oc-')
plt.title('picture')
plt.xlabel('x-label')
plt.ylabel('y-label')
plt.show()
Copy the code
If we want to display the title and label in Chinese, we just add a lineplt.rcParams['font.family']=['STFangsong']
, so that you can use the system font “imitation song”.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams['font.family'] = ['STFangsong']
xpoints=np.array([1.2.3.4.5])
ypoints=np.array([5.3.8.5.9])
plt.plot(ypoints,'oc-')
plt.title('Line chart')
plt.xlabel('Blog Writing Hours')
plt.ylabel('Number of rising powder')
plt.show()
Copy the code
In addition, we can also customize the font style:
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams['font.family'] = ['STFangsong']
xpoints=np.array([1.2.3.4.5])
ypoints=np.array([5.3.8.5.9])
plt.plot(ypoints,'oc-')
plt.title('Line chart',size='30',color='#ABCDEF')
plt.xlabel('number',size='15',color='blue')
plt.ylabel('price',size='20',color='m')
plt.show()
Copy the code
Set font size with size; Color Sets the font color. It can be abbreviated, written in full, or written in RGB hexadecimal.Finally, we can modify the positioning of the title and tag:
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams['font.family'] = ['STFangsong']
xpoints=np.array([1.2.3.4.5])
ypoints=np.array([5.3.8.5.9])
plt.plot(ypoints,'oc-')
plt.title('Line chart',loc='right',size='30',color='# 409882')
plt.xlabel('number',loc='left',size='15',color='blue')
plt.ylabel('price',loc='top',size='20',color='m')
plt.show()
Copy the code
-
The title() method provides loC arguments to set the location of the title display, which can be set to: ‘left’, ‘right’, and ‘center’. The default is ‘center’.
-
The xlabel() method provides loC arguments to set the position of the X-axis display, which can be set to: ‘left’, ‘right’, and ‘center’. The default value is ‘center’.
-
The ylabel() method provides loC arguments to set the position of the Y-axis display, which can be set to: ‘bottom’, ‘top’, and ‘center’. The default value is ‘center’.
🚀 4. Draw multiple maps
We can plot multiple plots using the Subplot () and subplots() methods in Pyplot.
The subplot() method requires a location to be specified when plotting, and the subplots() method can generate more than one at a time, requiring only ax of the generated object to be called. Subplot is recommended.
Subplot (nrows, ncols, index) subplot(nrows, ncols, index)
Subplot () divides the entire plot area into NRows and NCOLs columns, then numbers each subarea from left to right and top to bottom 1… N, the number of the upper left sub-area is 1, and the number of the lower right sub-area is N. The number can be set by using the index parameter.
from matplotlib import pyplot as plt
import numpy as np
#plot1
xpoints=np.array([0.2.4.6.8])
ypoints=np.array([0.3.6.9.12])
plt.subplot(1.2.1)
plt.plot(xpoints,ypoints)
plt.xlabel('x')
plt.ylabel('y')
plt.title('plot1')
#plot2
x=np.array([1.3.5.8])
y=np.array([10.3.6.2])
plt.subplot(1.2.2)
plt.plot(x,y)
plt.title('plot2',color='m')
plt.show()
Copy the code
You can see that plot1 and plot2 are added before plotPLT. Subplot (1, 2, 1)
andPLT. Subplot (1,2,2)
“, which means you divide the canvas into two columns, one on the left and two on the right, so plot1 is on the left and plot2 is on the right. It’s that simple.If we were to just plot the first area, delete the plot2 code and run it.
from matplotlib import pyplot as plt
import numpy as np
#plot1
xpoints=np.array([0.2.4.6.8])
ypoints=np.array([0.3.6.9.12])
plt.subplot(1.2.1)
plt.plot(xpoints,ypoints)
plt.xlabel('x')
plt.ylabel('y')
plt.title('plot1')
plt.show()
Copy the code
You can see that only Plot1 is on the left side of the canvas. There is no image on the right side, so it is empty. 🚤5. Draw scatter plots
Scatter plots can be drawn using the Scatter () method in PyPlot. The syntax format of Scatter () is as follows:
matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)
Copy the code
🎉 Parameter Description
X, y: array of the same length, which is the data point for which we are going to plot the scatter plot, input data.
S: the size of a point, 20 by default, or it can be an array with each argument being the size of the corresponding point.
C: The color of the dot, the default blue ‘B’, can also be an RGB or RGBA two-dimensional row array.
Marker: Style of point, default small circle ‘O’.
Cmap: Colormap, default None, scalar or the name of a Colormap, used only if C is a floating-point number group. If not, image.cmap.
Norm: Normalize, default None, data brightness between 0 and 1, only used if C is an array of floating point numbers.
Vmin, vmax: Brightness Settings, ignored in the presence of the norm parameter.
Alpha: Opacity setting, 0-1, default None, opacity.
Linewidths: The length of the mark point.
In fact, the above parameters do not need to remember all, the commonly used size and color can remember, after collection, forget to see at any time.
Let’s draw these 8 points on the canvas:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1.2.3.4.5.6.7.8])
y = np.array([1.4.9.16.7.11.23.18])
plt.scatter(x, y)
plt.show()
Copy the code
Let’s take a look at the effect:Let’s set the size of the scatter:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1.2.3.4.5.6.7.8])
y = np.array([1.4.9.16.7.11.23.18])
sizes = np.array([20.50.100.200.500.1000.200.100])
plt.scatter(x, y,sizes=sizes)
plt.show()
Copy the code
By defining sizes, the array elements are the size of each point:We can also customize the color of the points:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1.2.3.4.5.6.7.8])
y = np.array([1.4.9.16.7.11.23.18])
sizes = np.array([20.50.100.200.500.1000.200.100])
colors = np.array(["red"."green"."black"."orange"."purple"."beige"."cyan"."magenta"])
plt.scatter(x, y,sizes=sizes,c=colors)
plt.show()
Copy the code
Colors is a color array that stores the colors of each point:The Matplotlib module provides a number of available color bars. A color bar is like a list of colors, where each color has a value ranging from 0 to 100.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1.2.3.4.5.6.7.8])
y = np.array([1.4.9.16.7.11.23.18])
sizes = np.array([20.50.100.200.500.1000.200.100])
colors = np.array([10.20.30.40.50.60.70.80])
plt.scatter(x, y,sizes=sizes,c=colors,cmap='viridis')
plt.colorbar()
plt.show()
Copy the code
The cmap parameter is used to set the color bar. The default value is’ viridis’, after which the color value is set to an array of 0 to 100. To display a colorbar, use the plt.colorbar() method:
So that’s the basic use of all Pyplots, three in a row without getting lost.
Convince people that you have the willpower and attitude to get things done. Never give up until you get it done. Attitude is everything.