Common knowledge of Python drawing

Figure (), subplot() and subplots(), figure.add_subplot(), figure.add_axes(), plT.plot (), plt.xlim() and plt.ylim(), PLt.legeng (), plT.s how()

Figure () function

Function prototype:

matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, * *kwargs)
Copy the code

— Create a new figure, or activate an existing figure. Create a new canvas or activate an existing canvas

Parameters:

  • Num: int or STR, figure Calling figure without specifying an int is automatically passed from 1 incremented by default.
  • Figsize: specify the width and height of the figure, in inches; = (weight, height)
  • Dpi: Specifies the resolution of the drawing object, that is, the number of pixels per inch. The default value is 80. 1 inch is equal to 2.5cm
  • Facecolor: Background color, facecolor=’blue’
  • Edgecolor: border color
  • Frameon: Whether to display a frame

(1) For drawing only one figure, plt.figure() can be used instead, and the figure will be drawn on a canvas by default

import matplotlib.pyplot as plt
x=[1.2.3]
y1=[1.2.4]
y2=[1.4.8]
plt.plot(x,y1,color = "red",label = "red")
plt.plot(x,y2,color = "green",label = "green")
plt.legend()  # None This statement will not display the upper-right label
plt.show()
Copy the code

(2) If you want to draw two graphs, you must use plt.figure() twice. You can specify num or not specify num

import matplotlib.pyplot as plt
x=[1.2.3]
y1=[1.2.4]
y2=[1.4.8]

plt.figure()
plt.plot(x,y1,color = "red",label = "red")
plt.legend()  # None This statement will not display the lower-right label

plt.figure()
plt.plot(x,y2,color = "green",label = "green")
plt.legend()  # None This statement will not display the upper-right label
plt.show()
Copy the code

Of course, you can specify the same num, which will output the image on the same canvas as the output above

This gives us the opportunity to add images to a canvas later by calling plt.figure(num) and then calling functions that draw graphs, such as plt.plot(), etc.

Subplot () and subplots ()

Subplot () can divide the figure into n subplots, and then execute subplot() every time to generate a subplot of the corresponding position

Subplot () function prototype:

subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)`
Copy the code

Parameters:

  • Nrows: the number of rows in a subplot
  • Ncols: number of columns in subplot
  • Sharex: all subplots should use the same x-scale (adjusting xlim will affect all subplots)
  • Sharey: all subplots should use the same Y scale (adjusting ylim will affect all subplots)
  • Subplot_kw: Dictionary of keywords used to create subplots
  • **fig_kw: Other keywords for creating figure
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0.100)
Drawing # 1
plt.subplot(2.2.1)  # equivalent to plt.subplot(221)
plt.plot(x, x)
Drawing of 2 #
plt.subplot(2.2.2)
plt.plot(x, -x)
Drawing 3 #
plt.subplot(2.2.3)
plt.plot(x, x ** 2)
plt.grid(color='r', linestyle=The '-', linewidth=1,alpha=0.3)
Drawing 4 #
#plt.subplot(224)
#plt.plot(x, np.log(x))
plt.show()
Copy the code

The subplots() function is similar to the subplot() argument

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0.100)
# Draw the numerator
fig,axes=plt.subplots(2.2)   # return a canvas and scroll object that can be retrieved from the appropriate scroll and then called the drawing function
ax1=axes[0.0]
ax2=axes[0.1]
ax3=axes[1.0]
ax4=axes[1.1]

Drawing # 1
ax1.plot(x, x)
Drawing of 2 #
ax2.plot(x, -x)
Drawing 3 #
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle=The '-', linewidth=1,alpha=0.3)
Drawing 4 #
#ax4.plot(x, np.log(x))
plt.show()
Copy the code

Unlike subplot(), subplots() plot all plots at once and then calls the plot function

Figure objects can add subgraphs or drawing regions

figure.add_subplot()

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0.100)
Create a new figure object
fig=plt.figure()
# Create subgraph 1
ax1=fig.add_subplot(2.2.1)
ax1.plot(x, x)
Create a new subgraph 3
ax3=fig.add_subplot(2.2.3)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle=The '-', linewidth=1,alpha=0.3)
Create a new subgraph 4
ax4=fig.add_subplot(2.2.4)
ax4.plot(x, np.log(x))
plt.show()
Copy the code

You can see the same effect as subplot

figure.add_axes()

import numpy as np
import matplotlib.pyplot as plt

# new figure
fig = plt.figure()
# define data

x = np.array([1.2.3.4.5.6.7])

Create region ax1

# Percentage of figure, draw from 10% of figure and 80% of figure width and height
# The image should still be inside the figure

left, bottom, width, height = 0.1.0.1.0.8.0.8
Get the handle to the drawing
ax1 = fig.add_axes([left, bottom, width, height])  Get a region
ax1.plot(x,x**2 , 'r')
ax1.set_title('a1')
#plt.plot(x, y, 'r')

Add ax2 to ax1
left, bottom, width, height = 0.2.0.6.0.25.0.25
Get the handle to the drawing
ax2 = fig.add_axes([left, bottom, width, height])Get another region
ax2.plot(x,x**3.'b')
ax2.set_title('a2')
plt.show()
Copy the code

So you can draw the image anywhere in the figure, more flexible!

plt.plot()

Parameters:

  • X, y: x is optional. If x does not exist, it will default from 0 to n-1, which is the index of y.

  • FMT: STR, optional, defines the color and style of the line, such as “ro” is the red circle, “r–” is the red dotted line, this is a quick way to set the style, see the last keyboard arguments for more parameters.

  • Kwargs: Line2D properties, optional this is a bunch of optional content that you can specify, for example, “label” specifies the label of the line, “lineWidth” specifies the width of the line, etc

import matplotlib.pyplot as plt

a = [1.2.3.4] # y is the value of a, and x is the index of each element
b = [5.6.7.8]

plt.plot(a, b, 'g--', label = 'aa')
plt.xlabel('this is x')
plt.ylabel('this is y')
plt.title('this is a demo')
plt.legend() # display the sample
plt.show()
Copy the code

PLT. Xlim (“) and (PLT) ylim ()

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1.10.1000)
y = np.random.rand(1000)

plt.scatter(x,y,label="scatter figure")
plt.legend()

plt.xlim(1.10) # specify the scale values of x and y
plt.ylim(0.1)
plt.show()
Copy the code

plt.legeng()

Legend ——–(translation: map or icon)

1. Set the position of the column

plt.legend(loc=' ')# Fill in the position, such as: upper left, legend in the upper left corner
Copy the code

2. Set the legend font size

fontsize : int or float or{xx - small, 'X-ray small', 'small', 'medium', 'large', 'x - large', 'xx - large}'Copy the code

3. Set the legend border and background

Plt. legend(loc='best',edgecolor='red') # Plt.legend (loc='best',facecolor='blue') # set the legend background colorCopy the code

4. Set the legend title

legend = plt.legend(["BJ"."SH"], title='Beijing VS Shanghai')
Copy the code
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.10.1)
plt.plot(x,x,'r--',x,np.cos(x),'g--',marker=The '*')
plt.xlabel('row')
plt.ylabel('cow')
plt.legend(["BJ"."SH"],loc='upper left',title='Beijing VS Shanghai'
         # ,frameon=False
          ,edgecolor='green'
          ,facecolor='black')
plt.show()
Copy the code

plt.show()

Plt.show () is used to show images.

It is possible that you are using an interactive programming environment such as IPython. For example, Jupyter Notebook is also internal and IPython is called because IPython can output results in a timely manner. If you want an IDE (integrated development environment such as Pycharm), you must use plt.show().