(Study notes) Arrangement of basic drawing functions under matplotlib.pyplot module

matplotlib version: 3.7.1

python version: 3.10.12

# 模块引入
import matplotlib.pyplot as plt

1. plt.plot() function

Mainly used for drawing, drawing points and lines.
grammar:

plt.plot(x,y,format_string,**kwargs)

Parameter introduction:

x: data for x-axis, can be scalar, tuple, list
y: data for y-axis, can be scalar, tuple, list
format_string: string controlling the format of the curve, optional
**kwargs: second group or more Multiple (x, y, format_string), can draw multiple curves.

Among them, format_string: consists of color characters, style characters and mark characters
Color character example:
'b': blue
'c': turquoise
'g': green
'k': black
'm': magenta
'r': red
'w': white
'y': yellow

Examples of style characters :
'‐' Solid line
'‐‐' Dashed line
'‐.' Dotted line
':' Dashed line
'' ' ' No line

Examples of mark characters :
'.' point mark
',' pixel mark (very small point)
'o' solid circle mark
'v' inverted triangle mark
'^' upper triangle mark
'>' right triangle mark
'<' left triangle mark


**kwargs This is a dictionary with many optional parameters: the
commonly used ones are:
color: specify the color
lable: the label of the line
linestyle: the style of the line
linewidth: the width of the line

1.1 plt.plot(x, y)

x = [1, 2, 4, 7]
y = [5, 6, 8, 10]

# 传入两个列表,x为横坐标,y为纵坐标
plt.plot(x, y)
plt.show()

insert image description here

x = [1, 2, 4, 7]
y = [5, 6, 8, 10]
y1 = [11, 15, 16, 19]

# 传入两个列表,x为横坐标,y为纵坐标
plt.plot(x, y) # 用红色的原点,标出点,用实线连接
plt.plot(y1)   #x可以省略,默认从[0, 1, 2, 3, N-1 ]递增
plt.show()

insert image description here
You can also pass in two or more sets of parameters

x = [1, 2, 4, 7]
y = [5, 6, 8, 10]
x1 = [10, 12, 14, 18]
y1 = [11, 15, 16, 19]

# 传入两个列表,x为横坐标,y为纵坐标
plt.plot(x, y, 'ro-', x1, y1, 'bo--')
plt.show()

insert image description here

You can also pass a 2D array

lst1 = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
lst2 = [[2, 3, 2], [3, 4, 3], [4, 5, 4]]
# 传入两个列表,x为横坐标,y为纵坐标
plt.plot(lst1, lst2,  'bo--')
plt.show()

It is observed that the first column of the two-dimensional array is a set of coordinates, the second column is a set of coordinates, and the third column is a set of coordinates.
insert image description here

1.2 plt.plot(x, y, **kwargs)

Parameters that control lines and points.

x = [1, 2, 4, 7]
y = [5, 6, 8, 10]
# 蓝色,线宽20,圆点,点尺寸50,点填充红色,点边缘宽度6,点边缘灰色
plt.plot(x, y, color="blue", linewidth=10, marker="o", markersize=50,
         markerfacecolor="red", markeredgewidth=6, markeredgecolor="grey")
plt.show()

insert image description here

2. plt.xlable(), plt.ylable()

Give the x/y axis a name.

Syntax: plt.xlable(string)
string: string format name

x = [1, 2, 4, 7]
y = [5, 6, 8, 10]

plt.xlabel('size')
plt.ylabel('price')
plt.plot(x, y, 'ro')
plt.show()

insert image description here

3. plt.title()

Give the table a title.

Syntax: plt.title(string)
shring: title in string format.

x = [1, 2, 4, 7]
y = [5, 6, 8, 10]

plt.xlabel('size')
plt.ylabel('price')
plt.title('house price')
plt.plot(x, y, 'ro')
plt.show()

insert image description here

4. plt.show()

Display the coordinate plot.
Several functions above already contain this example.

5.plt.subplot()

Divide a figure into n rows and m columns, and select the kth position for drawing (counting from 1).

Syntax: plt.subplot(nrows,mcols,k)

# 把画布分成两行两列,画在第四个位置
x = [1, 2, 4, 7]
y = [5, 6, 8, 10]
plt.subplot(224)
plt.xlabel('size')
plt.ylabel('price')
plt.title('house price')
plt.plot(x, y, 'ro')
plt.show()

insert image description here

plt.subplots()

语法:fig, ax = plt.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

parameter settings:

  • nrows/ncols: Set the number of rows and columns of the icon, the default is 1
  • sharex/sharey: Set whether x and y are shared attributes, the default is false, and can be set to 'none', 'all', 'row' or 'col'. False or none for each subplot's x or y axis to be independent, True or 'all': all subplots share an x ​​or y axis, 'col': set each subplot column to share an x ​​or y axis.
  • squeeze: Boolean value, the default is True, indicating that extra dimensions are squeezed out from the returned Axes (axes) object, for N*1 or 1*N subplots, return a 1-dimensional array, for N*M, N>1 and M>1 returns a 2D array. If set to False, no extrusion is performed and a 2D array of Axes instances is returned, even if it ends up being 1x1.
  • subplot_kw: optional, dictionary type. Pass the keys of the dictionary to add_subplot() to create each subplot.
  • gridspec_kw: optional, dictionary type. Pass the key of the dictionary to the GridSpec constructor to create a subgraph and place it in the grid (grid)
  • **fig_kw: pass detailed keyword arguments to the figure() function
import matplotlib.pyplot as plt
import numpy as np

# 创建一些测试数据 -- 图1
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# 创建一个画像和子图 -- 图2
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# 创建两个子图 -- 图3
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# 创建四个子图 -- 图4
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)

# 共享 x 轴
plt.subplots(2, 2, sharex='col')

# 共享 y 轴
plt.subplots(2, 2, sharey='row')

# 共享 x 轴和 y 轴
plt.subplots(2, 2, sharex='all', sharey='all')

# 这个也是共享 x 轴和 y 轴
plt.subplots(2, 2, sharex=True, sharey=True)

# 创建标识为 10 的图,已经存在的则删除
fig, ax = plt.subplots(num=10, clear=True)

plt.show()

insert image description here

insert image description here


Example of using this function to draw a scatterplot:

X_train = np.array([[1.0], [2.0]], dtype=np.float32)           #(size in 1000 square feet)
Y_train = np.array([[300.0], [500.0]], dtype=np.float32)       #(price in 1000s of dollars)

fig, ax = plt.subplots(1,1)
ax.scatter(X_train, Y_train, marker='x', c='r', label="Data Points")
ax.legend( fontsize='xx-large')
ax.set_ylabel('Price (in 1000s of dollars)', fontsize='xx-large')
ax.set_xlabel('Size (1000 sqft)', fontsize='xx-large')
plt.show()

insert image description here

6. plt.figure()

Create an object of matplotlib functions, which is the top-level container. We can use this object to perform drawing operations.

Syntax: fig = plt.figure()
creates a fig object

fig.add_subplot()

add a subgraph

Syntax: ax = fig.add_subplot(111)
Add a subplot with one row and one column

Reference website:
Cainiao Tutorial

Guess you like

Origin blog.csdn.net/weixin_45153969/article/details/131981939