Detailed explanation of python plt drawing (plt. version)

1. Introduction to plt

  The drawing tool in python: matplotli, which is specially used for drawing.

2. Installation and import

  Toolkit installation:

conda install matplotli

  import:

import matplotlib.pyplot as plt

3. Instructions for use

1. Use plt.plot and plt.show to draw and display images

plt.plot(x, y, color, linestyle, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, alpha, linewidth)

(1) Curve color (color is abbreviated as c):

r g b y k
red green blue yellow black

(2) Point type (marker):

+ o * . x s d ^ v p
plus the circle Asterisk solid point Cross square diamond shape upper triangle lower triangle Pentagram

(3) Line style (linestyle is abbreviated as ls):

- -.
solid line dotted line Dotted line dotted line

(4) Description of remaining parameters

markersize abbreviated as ms (marker size): real number

markeredgewidth abbreviated as mew (marker edge width): real number

markeredgecolor abbreviated as mec (marker edge color): any value in the color option

markerfacecolor abbreviated as mfc (marker surface color): any value in the color option

alpha (transparency): floating point number between [0,1]

linewidth (line width): real number

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y2 = [1, 4, 9, 16, 25, 36, 49, 64, 81]

# 绘制的曲线属性设置
line1, = plt.plot(x, y, color='r', marker='d', linestyle='--', markersize=6, alpha=0.5, linewidth=3)
line2, = plt.plot(x, y2, color='g', marker='*', linestyle='-', markersize=6, alpha=0.5, linewidth=3)
# plt.plot(x, y, 'rd--')  # 可以使用这种方式进行画图的属性设置

# x,y坐标轴名称设置,可以同时设置标签的字体大小颜色等
plt.xlabel(u'x坐标轴', fontsize=14, color='r')
plt.ylabel(u'y坐标轴', fontsize=14, color='b')

# 显示曲线图像
plt.show()
plt.show() displays the result

2. Image property setting

(1) Coordinate axis label setting

# 注意,要使用中文的话,需要在引入库后,添加下列代码
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

# x,y坐标轴名称设置,可以同时设置标签的字体大小颜色等
plt.xlabel(u'x坐标轴', fontsize=14, color='r')
plt.ylabel(u'y坐标轴', fontsize=14, color='b')

(2) Image title setting

# 设置图表标题
plt.title(u"图像标题", fontsize=14, color='k')

(3) Legend settings

# 添加图例
plt.legend([line1, line2], ["Weekend", "Weekday"], loc='upper left')

(4) Coordinate axis range setting

# 设置x轴的范围为[0, 100],y轴的范围为[0, 100], 或者通过xlim, ylim设置XY轴的范围上下限
plt.axis([0, 10, 0, 100])
# plt.xlim(0, 10)
# plt.ylim(0, 100)

(5) Coordinate interval setting

plt.xticks (parameter 1, parameter 2, parameter 3) is used to realize the setting of the x-axis and y-axis coordinate interval (that is, the axis mark).

  • Parameter one: the parameter of x or y
  • Parameter 2: The number of new tags must be the same as the number of parameters
  • Parameter three: rotation angle
# 坐标间隔及标签设定
a = [1, 2, 3, 4, 5]
labels = ['A', 'B', 'C', 'D', 'E']
plt.xticks(a, labels, rotation=0)

(6) Add grid

# 添加网格
plt.grid(visible=True, axis='x')  # 只显示x轴网格线
plt.grid(visible=True, axis='y')  # 只显示y轴网格线
final display effect

all codes

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y2 = [1, 4, 9, 16, 25, 36, 49, 64, 81]

# 绘制的曲线属性设置
line1, = plt.plot(x, y, color='r', marker='d', linestyle='--', markersize=6, alpha=0.5, linewidth=3)
line2, = plt.plot(x, y2, color='g', marker='*', linestyle='-', markersize=6, alpha=0.5, linewidth=3)
# plt.plot(x, y, 'rd--')  # 可以使用这种方式进行画图的属性设置

# x,y坐标轴名称设置,可以同时设置标签的字体大小颜色等
plt.xlabel(u'x坐标轴', fontsize=14, color='r')
plt.ylabel(u'y坐标轴', fontsize=14, color='b')

# 设置图表标题
plt.title(u"图像标题", fontsize=14, color='k')

# 添加图例
plt.legend([line1, line2], ["Weekend", "Weekday"], loc='upper left')

# 设置x轴的范围为[0, 100],y轴的范围为[0, 100], 或者通过xlim, ylim设置XY轴的范围上下限
plt.axis([0, 10, 0, 100])
# plt.xlim(0, 10)
# plt.ylim(0, 100)

# 坐标间隔及标签设定
a = [1, 2, 3, 4, 5]
labels = ['A', 'B', 'C', 'D', 'E']
plt.xticks(a, labels, rotation=0)

# 添加网格
plt.grid(visible=True, axis='x')  # 只显示x轴网格线
plt.grid(visible=True, axis='y')  # 只显示y轴网格线

# 显示曲线图像
plt.show()


3. Draw multiple graphs on one image

  • Use plt.figure(arg) to create an artboard, arg is the name of the artboard
  • Use the plt.subplot(arg1, arg2, arg3) method to create a drawing paper, and select the current drawing paper and draw. Among them, ag1 represents the row, arg2 represents the column, and arg3 represents the image
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

x = np.arange(0, 100, 10)

plt.figure(1)  # 生成第一个图,且当前要处理的图为fig.1

plt.subplot(1, 2, 1)  # fig.1是一个一行两列布局的图,且现在画的是左图
y1 = np.exp(x)
plt.plot(x, y1, color="r", linestyle="-", marker="^", linewidth=1)  # 画图
plt.xlabel("x")
plt.ylabel("y1")

plt.figure(1)  # 当前要处理的图为fig.1,而且当前图是fig.1的左图
plt.subplot(1, 2, 2)  # 当前图变为fig.1的右图
y2 = np.exp(1.5 * x)
plt.plot(x, y2, color="b", linestyle="-", marker="v", linewidth=1)
plt.xlabel("x")
plt.ylabel("y2")

plt.show()
Multi-image display

4. Draw dual axes on one graph

Mainly add coordinate axes through fig.add_subplot(), and then draw the coordinate axes on the same graph

import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

# 生成数据
x = np.arange(1, 12, 4)
y = np.arange(1, 4, 1)
x2 = x * 10
y2 = y ** 2

# 设置画布大小
width, height = 16, 14  # 单位为cm;因为保存图片时使用 bbox_inches = 'tight' 可能使图片尺寸略微放大,所以此处宽度设置得略小

# 设置刻度线在坐标轴内
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'

# 绘制图像
lns = []  # 用于存储绘图句柄以合并图例的list

# 创建画布并设置大小
fig = plt.figure()
fig.set_size_inches(width / 2.54, height / 2.54)  # 因为画布输入大小为厘米,此处需转换为英寸,所以除以2.54

# 通过 add_subplot 方式创建两个坐标轴,相当于在同一个子图上叠加了两对坐标系
ax = fig.add_subplot(111, label="1")
ax2 = fig.add_subplot(111, label="2", frame_on=False)

# 绘制图1并将绘图句柄返回,以便添加合并图例
lns1 = ax.plot(x, y, color='r', label='r')
lns = lns1
lns2 = ax2.plot(x2, y2, color='b', label='b')
lns += lns2

# 调整第二对坐标轴的label和tick位置,以实现双X轴双Y轴效果
ax2.xaxis.tick_top()
ax2.yaxis.tick_right()
ax2.xaxis.set_label_position('top')
ax2.yaxis.set_label_position('right')

# 设置坐标轴标注
ax.set_xlabel("X1", color='r', fontsize=12)
ax.set_ylabel("Y1", color='r', fontsize=12)
ax2.set_xlabel('X2', color='b', fontsize=12)
ax2.set_ylabel('Y2', color='b', fontsize=12)

# 设置图表标题
fig.suptitle("Title", fontsize=12)

# 设置坐标轴刻度颜色
ax.tick_params(axis='x', colors='r')
ax.tick_params(axis='y', colors='r')
ax2.tick_params(axis='x', colors='b')
ax2.tick_params(axis='y', colors='b')

# 设置坐标轴线颜色
ax.spines["left"].set_color("r")  # 修改左侧颜色
ax.spines["right"].set_color("b")  # 修改右侧颜色
ax.spines["top"].set_color("b")  # 修改上边颜色
ax.spines["bottom"].set_color("r")  # 修改下边颜色

# 添加图例
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0, fontsize=12)
plt.tight_layout()
plt.show()

Guess you like

Origin blog.csdn.net/qq_30150579/article/details/128001322