Python 优雅绘图

使用python实验的时候需要绘制各种结果图,这里将介绍如何使用常用的绘图包进行绘图

参考资料:Matplotlib 教程 | 菜鸟教程 (runoob.com)

画图的关键元素包括

  • 数据
  • 图例
  • 线型
  • 坐标轴
  • 表头
  • 网格,辅助线(看情况)

快速入门

简单二维曲线图

这里使用numpy 里面的张量和 matplotlib 来简单绘制图形,简单的图形只需要确定坐标轴和数据就可以了。

1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt
import numpy as np

# 表示输入的x轴和y轴数据,用numpy生成的 0,6的张量和 0,100的张量表示输入的数据
xpoints = np.array([0, 6])
ypoints = np.array([0, 100])

# 根据输入绘制线性图
plt.plot(xpoints, ypoints)
# 图像渲染
plt.show()

常用的绘图类型

1
2
3
4
5
6
7
plot():用于绘制线图和散点图
scatter():用于绘制散点图
bar():用于绘制垂直条形图和水平条形图
hist():用于绘制直方图
pie():用于绘制饼图
imshow():用于绘制图像
subplots():用于创建子图

线图

1
2
3
4
5
6
7
8
9
10
11
# 画单条线
plt.plot(x, y, [fmt2]) #第一个参数x数据,第二个是y数据,第三个是线型 (也可以选择不设置)
# 画多条线
plt.plot(x1, y1, [fmt], x2, y2, [fmt2]) # 多根线的数据和线型
# 多根线也可以s可以重复单线画法
plt.plot(x, y, [fmt2])
plt.plot(x, y, [fmt2])
# 常用的线型设置
颜色字符:'b' 蓝色,'m' 洋红色,'g' 绿色,'y' 黄色,'r' 红色,'k' 黑色,'w' 白色,'c' 青绿色,'#008000' RGB 颜色符串。多条曲线不指定颜色时,会自动选择不同颜色。
线型参数:'‐' 实线,'‐‐' 破折线,'‐.' 点划线,':' 虚线。
标记字符:'.' 点标记,',' 像素标记(极小点),'o' 实心圈标记,'v' 倒三角标记,'^' 上三角标记,'>' 右三角标记,'<' 左三角标记...等等。

此外还可以点的类型,具体看推荐文档

坐标轴

1
2
plt.xlabel("x - label")
plt.ylabel("y - label")

表题

1
plt.title("plot title")

如何使用中文字体见参考资料

网格线

1
2
3
4
5
6
# 默认网格
plt.grid()
plt.grid(axis='x') # 设置 y 就在轴方向显示网格线
plt.grid(axis='y') # 设置 x 就在轴方向显示网格线
# 设置线网格的
plt.grid(color = 'r', linestyle = '--', linewidth = 0.5)

绘制多个子图

  • 先确定好x y的数据
  • 绘图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

import matplotlib.pyplot as plt
import numpy as np

#plot 1:
xpoints = np.array([0, 6])
ypoints = np.array([0, 100])

plt.subplot(1, 2, 1) # 1 行2列 第一个子图
plt.plot(xpoints,ypoints)
plt.title("plot 1")

#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])

plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("plot 2")

plt.suptitle("RUNOOB subplot Test")
plt.show()

图例说明

图例属性 参考 matplotlib.pyplot.legend()参数详解_pyplot legend-CSDN博客

legend 的loc 的属性

upper left upper center upper right
center left center center right
lower left lower center lower right
1
2
3
4
5
6
7
8
# 绘制两条线,zuo's
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

# 添加图例
plt.legend()
# 图例里面可以设置图例的摆放位置
plt.legend(loc='upper right')

快捷模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import matplotlib.pyplot as plt
import numpy as np

# 1.数据
xpoints = np.array([0, 6])
xpoints2 = np.array([0,3 ])
ypoints = np.array([0, 100])

# 2.线型和图例设置
plt.plot(xpoints, ypoints,'-.b',label='line_1')
plt.plot(xpoints2, ypoints,'-y',label='line_1')

# 3.图例设置
plt.legend(loc='center right',fontsize='small')

# 4.图题设置(自选)
plt.title('test title')

# 5.XY轴设置
plt.xlabel("x - label")
plt.ylabel("y - label")

#渲染
plt.show()