SoFunction
Updated on 2024-11-10

Teach you to plot with python's matplotlib library.

I. Preface

python's matplotlib library is powerful enough to draw various types of images.
The first thing to do is to install some basic libraries such as numpy, matplotlib or pandas.

II. Basic commands

First, we introduce the basic commands that are commonly used when drawing:

(x,y) is the plotting command.
① Basic drawing:

(x, y)

② Set the color:

color attribute
You can not set the color manually if you don't have any special requirements, and the color will be assigned automatically if you want to draw different lines on one drawing. You can also use the same effect.

(x, y, color = 'red')

③ Set the line type:

lineStyle property
You can choose from '-', '-', '-.' , ':', 'None', '', '', 'solid', 'dashed', 'dashdot', 'dotted' and these types of .

(x, y, lineStyle = 'dashdot')

④ Set the labeling type:

Marker Attributes
There are different markers to choose from, such as 'o', '*', 'x'.

(x, y ,marker='x')

⑤ Set the legend:

label attribute.

(x, y ,marker='o',label='Language achievement')
(x, y ,marker='*',label='Math scores')
(x, y ,marker='x',label='English Language Achievement')

Just so the legend will not be displayed, you also need to add the loc is the location of the settings, see later to explain.

(loc='upper left')

III. Normal display of Chinese:

① windows system:

[''] = ['sans-serif']
['-serif'] = ['SimHei']

mac system:
This is how it is set here, and it can also be set to other Chinese fonts.

[""] = 'Arial Unicode MS'

② Normal display symbols:

['axes.unicode_minus'] = False

IV. Setting up drawings or sub-drawings

① If you only draw a picture, you can, figsize is set to the ratio of the size of the picture in the x-axis and y-axis direction. Here you have to set it well or else the picture may not be displayed completely, if you save it through the savefig command, it is also in accordance with this ratio to save the picture.

f = (figsize=(8,6))

Or, although it is through the subplots command, there is only one subplot by default without specifying nrows and ncols.

f, ax = (figsize=(8,6))

ax represents the current axis.

ax = ()

If there are multiple subgraphs:
rows are rows, ncols are columns, and figsize is the size of the image.

f, ax = (nrows=2,ncols=1,figsize=(8,6),facecolor='white')

either one or the other

fig = ()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
(x,y)
(x,z)

either one or the other

ax1 = (2,1,1)
ax2 = (2,1,2)
(x,y)
(x,z)

Other attributes: the first attribute marks the name of the window, dpi sets the resolution.

f = ('Results window',figsize=(8,6),facecolor='white',dpi=100)

窗口名称

② Set the background color of the picture:

f = (figsize=(8,6),facecolor='blue')

设置facecolor

To set the image foreground color, use the

(facecolor='white')

设置颜色

V. Set the x-axis or y-axis related attributes:

① Set the x-axis scale:
You need to specify the position of the label, the specific value of the label, and you can specify the size by fontsize.

x = [0,2,4,6,8]
x_label = ['First semester','Second semester','Third semester','Fourth semester','Fifth semester']
(x, x_label,fontsize=13)

The xticks here support latex.

x_label = [r'$e^x$',r'$x_1^2$',r'$\lambda$',r'$\frac{1}{2}$',r'$\pi$']

在这里插入图片描述

Sometimes there may be a lot of values labeled and we want to display the x-axis scale vertically:
Simply add the '\n' line break to the x_label where you want it.

x = [0,2,4,6,8]
x_label = ['The \nth one \nth school \nth period','Second \n semester','The \nthree\nthird/nth school/nth period','Fourth \n semester','Fifth \n semester']
(x, x_label,fontsize=13)# Here's a chart

换行符x轴

② Set the label of the x-axis:
These two commands do the same thing.

(u"Semester.")
ax.set_xlabel(u"Semester.")#set upxLabeled values of the axes

标签

xlabel also supports latex

(u"$x^2$")

标签

③ Set the range of the x-axis:
These two commands do the same thing.
There is generally no need to specify a range artificially; the program automatically determines a range based on the maximum and minimum values entered.

(0,100)
ax.set_xlim(0,100)

设置x轴范围

Setting the attributes associated with the y-axis is the same method as the attributes associated with the x-axis, you just need to replace the x with a y.

VI. Setting the title:

fontsize is the size, and fontweight specifies bold. The following two commands serve the same purpose.

('Line graph of changes in Ming's grades from the first to the fourth semester',fontsize=18,fontweight='bold')
ax.set_title('Line graph of changes in Ming's grades from the first to the fourth semester',fontsize=18,fontweight='bold')

title

Here the program will automatically put the title in a suitable location, of course, it is inevitable that the title is not the position we want, which can be specified by the x or y attribute, to set the location of the title. Normal range is [0,1] can be set to negative zero or a few, need to try more, if set beyond the picture will not see the title of the range.
For example, here I set y=-0.1 and you can see the title goes to the bottom.

('Line graph of changes in Ming's grades from the first to the fourth semester',fontsize=18,fontweight='bold',y=-0.1)

手动设置y

VII. Setting up the legend:

Act I:
Label it well when you draw it.

(x, y[0,:],marker='o',label='Language achievement')
(x, y[1,:],marker='*',label='Math scores')
(x, y[2,:],marker='x',label='English Language Achievement')
(loc='upper left')

Law II:
Not written in plot, uniformly written in legend.
You can specify the corresponding curve, here the curve definition must be followed by ',', otherwise it will report an error.

a,=(x, y[0,:],marker='o')
b,=(x, y[1,:],marker='*')
c,=(x, y[2,:],marker='x')
((a,b,c),('Language achievement','Math scores','English Language Achievement'),loc='upper left')

or not specify the corresponding curve.

(('Language achievement','Math scores','English Language Achievement'),loc='upper left')

The way of not specifying the corresponding curve is not recommended, sometimes you don't want to add legend to every curve, and you can leave the label attribute off for the curves you don't want to add legend to. This way will add legend in the order of plot, and will not skip the curves that don't want to add legend, unless it is the last curve, which won't be added if it is not written.
The command for LEGEND can only be set via plt, if there are multiple subplots

ax = (2,1,1)

This way operations on plt can operate on subgraphs.

VIII. Perform labeling:

You need to write loops for labeling, one by one, you can't write (x,y,"%s"%str(y)) like this, you won't be labeling a bunch at once.
fontsize is to set the font of the annotation. It is the same with ax.

for i in range(len(x)):
	(x[i],y[i],"%s"%str(y[i]), fontsize=12)
	#(x[i],y[i],"%s"%str(y[i]), fontsize=12)

标注

Often appear the legend to the picture content to block the situation, here you can also specify the position of the legend.

legend挡住图片

The position of the legend can be adjusted with the bbox_to_anchor property.

(bbox_to_anchor=(1.05, 1), loc=2)

调整图片

The legend has a number of other attributes that

IX. Save the picture:

('Chart of changes in Ming's grades.png')

X. Display pictures:

()

XI. Delete the border:

There are four directions here, and you can choose which direction to delete the border.

['right'].set_visible(False)
['top'].set_visible(False)
['bottom'].set_visible(False)
['left'].set_visible(False)

XII. Display/non-display grid:

(True)
(False)

to this article about teach you to learn to draw through python's matplotlib library is introduced to this article, more related to python's matplotlib library content, please search for my previous posts or continue to browse the following related articles I hope that you will support me in the future more!