Common knowledge of Python drawing

Time:2021-12-1

Common knowledge of Python drawing

Figure (), subplot (), subplots (), figure. Add_ subplot()、figure.add_ Axes(), PLT. Plot(), PLT. Xlim(), PLT. Ylim(), PLT. Legeng(), PLT. Show()

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)

–Create a new figure, or activate an existing figure

Parameters:

  • Num: int or STR, unique number of figure. If you do not specify to call figure, you will increase the auto incoming int from 1 by default.
  • Figsize: Specifies the width and height of figure, in inches= (weight,height)
  • DPI: Specifies the resolution of the drawing object, that is, how many pixels per inch. The default value is 80. 1 inch is equal to 2.5cm. A4 paper is 21 * 30cm paper
  • Facecolor: background color, facecolor =’Blue ‘
  • Edgecolor: border color
  • Frameon: Show border

(1) For drawing only one picture, it can not be usedplt.figure(), the graphics 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() # without this statement, the label in the upper right corner will not be displayed
plt.show()

Common knowledge of Python drawing

(2) If you want to draw two pictures, you must usePLT. Figure() twice, you can specify num or not. Calling it twice will add 1 by default

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() # without this statement, the label in the lower right corner will not be displayed

plt.figure()
plt.plot(x,y2,color = "green",label = "green")
PLT. Legend() # without this statement, the label in the upper right corner will not be displayed
plt.show()

Common knowledge of Python drawing

Of course, you can also specify the same num, which will be consistent with the above output results and output images in the same canvas

This also provides an opportunity for us to add images to a canvas later, just callplt.figure(num)And then call the function that draws graphics, for example.plt.plot()Wait.

Subplot() and subplots()

Subplot () can divide the figure into n subgraphs, and then execute subplot () once each time to generate a subgraph corresponding to the position

Prototype of subplot() function:

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

Parameters:

  • Nrows: number of rows of subplot
  • Ncols: number of columns in subplot
  • Sharex: all subplots should use the same X-axis scale (adjusting Xlim will affect all subplots)
  • Share Y: all subplots should use the same Y-axis scale (adjusting ylim will affect all subplots)
  • subplot_ KW: keyword dictionary used to create each subplot
  • **fig_ KW: other keywords when creating figure
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#Drawing 1
Plot.subplot (2,2,1) # equivalent to plot.subplot (221)
plt.plot(x, x)
#Drawing 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='--', linewidth=1,alpha=0.3)
#Drawing 4
#plt.subplot(224)
#plt.plot(x, np.log(x))
plt.show()

Common knowledge of Python drawing

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

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 100)
#Partition subgraph
Fig, axes=plt.subplots (2,2), return to a canvas and drawing object, you can take out the painted axis and call 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 2
ax2.plot(x, -x)
#Drawing 3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#Drawing 4
#ax4.plot(x, np.log(x))
plt.show()

Common knowledge of Python drawing

Unlike subplot (), subplots () draws all the axes at once, and then calls the drawing function

The figure object can add subgraphs or drawing areas

figure.add_subplot()

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#New figure object
fig=plt.figure()
#New sub Figure 1
ax1=fig.add_subplot(2,2,1)
ax1.plot(x, x)
#New sub Figure 3
ax3=fig.add_subplot(2,2,3)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#New sub Figure 4
ax4=fig.add_subplot(2,2,4)
ax4.plot(x, np.log(x))
plt.show()

Common knowledge of Python drawing

It can be seen that the effect is no different from that of 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])

#New area ax1

#The percentage of figure is drawn from 10% of figure, and the width and height are 80% of figure
#The image should still be inside figure

left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
#Gets the handle to the drawing
ax1 = fig.add_ Axes ([left, bottom, width, height]) # gets an area
ax1.plot(x,x**2 , 'r')
ax1.set_title('a1')
#plt.plot(x, y, 'r')

#Add a new area AX2, nested in ax1
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
#Gets the handle to the drawing
ax2 = fig.add_ Axes ([left, bottom, width, height]) # gets another area
ax2.plot(x,x**3, 'b')
ax2.set_title('a2')
plt.show()

Common knowledge of Python drawing

In this way, you can draw images anywhere in figure, which is more flexible!

plt.plot()

Parameters:

  • x. Y: X is optional. If X does not exist, it will default from 0 to n-1, that is, the index of Y.
  • FMT: STR, optional, operation to define the color and style of the line. For example, “ro” is a red circle and “R –” is a red dotted line. This is a quick method to set the style. For more parameters, please refer to the last keyboard arguments.
  • Kwargs: line2d properties, optional this is a lot of optional content, which can specify many contents, such as “label” specifies the label of the line, “linewidth” specifies the width of the line, and so on
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() # displays the sample
plt.show()

Common knowledge of Python drawing

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) # specifies the scale values for X and y
plt.ylim(0,1)
plt.show()

Common knowledge of Python drawing

plt.legeng()

Legend ——– (Translation: (map or icon) legend, description and explanation)

1.Set column position

Plt.legend (LOC = '') # fill in the position, for example: upper left, then the legend is in the upper left corner

2.Set legend font size

fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

3.Set legend border and background

PLT. Legend (LOC ='best ', frameon = false) # remove the legend border
PLT. Legend (LOC ='best ', edgecolor ='Red') # sets the legend border color
PLT. Legend (LOC ='best ', facecolor ='Blue') # sets the background color of the legend. If there is no border, the parameter is invalid

4.Set legend title

legend = plt.legend(["BJ", "SH"], title='Beijing VS Shanghai')
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='*')
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()

Common knowledge of Python drawing

plt.show()

plt.show()Is to display pictures. For someone who says why I didn’t use this function, I can display pictures as well??

That’s probably what you’re usingIPythonThis kind of interactive programming environment, such asjupyter notebookIt also belongs to the internal callIPython, because this class can output results in time. If you want an IDE (integrated development environment, such as pycharm), you must use itplt.show()

Recommended Today

Game case | application evolution and practice of service mesh in happy games

author Chen Zhiwei, Tencent level 12 background expert engineer, is now responsible for the public background technology research and development and team management of happy game studio. Rich experience in micro service distributed architecture and game background operation and maintenance research and development. preface The background of happy game studio is a distributed micro service […]