matplotlib笔记

matplotlib的一些使用整理笔记,详细使用参见官网

交互绘图

matplotlib有交互模式,可以通过交互模式实现动态绘图。主要通过循环绘图==>清除上一幅图片==>绘图,来实现动态图表。

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

# plt.ion() 打开交互模式
# plt.ioff() 关闭交互模式
# plt.clf() 清除图像(figure)
# plt.cla() 清除Axes
# plt.pause() 交互模式下暂停并展示图表

X, Y = np.random.rand(2, 10)
x, y = [], []
plt.ion()
for i in range(len(X)):
plt.clf() # 不删除图表一样可以运行,但之前图表会一直占用内存
x.append(X[i])
y.append(Y[i])
plt.scatter(x, y)
plt.pause(0.2)
plt.ioff()
plt.show()

全局变量

matplotlib提供了变更全局变量的方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib as mpl
# 方式一
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
# 方式二
mpl.rc('lines', linewidth=2, color='r')

# 中文乱码指定字体
plt.rcParams['font.sans-serif'] = ['SimHei']
# 正常显示负号
plt.rcParams['axes.unicode_minus'] = False

# 如果不想每次都指定这些内容,可以将这些内容直接写入到默认配置文件matplotlibrc
mpl.matplotlib_fname() # 配置文件路径

风格

matplotlib提供了不少的风格选项,可以自己指定,或者使用默认风格。

1
2
3
4
5
6
7
8
# 输出可用风格
print(plt.style.availabel)
# 指定全局风格
plt.style.use('ggplot')
# 只想临时使用某种风格,而不改变全局风格
with plt.style.context('ggplot'):
plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()

注释

在图表中加入箭头类型的注释文本,具体使用参见网址

1
plt.annotate(text, xy, xytext, arrowprops)

坐标轴

坐标轴设定很多,这里就写一些常用的。

1
2
3
4
5
6
7
8
9
10
11
12
# 坐标轴标签
plt.xlabel("X",fontsize=10,fontweight='bold')
# 坐标轴范围
plt.axis(xlim=(xmin, xmax), ylim=(ymin, ymax))
plt.axis([xmin, xmax, ymin, ymax])
plt.xlim(xmin, xmax)
# 不显示坐标轴
plt.axis('off')
# 横纵坐标轴刻度相等
plt.axis('equal')
# 坐标轴刻度标签
plt.xticks([0,1,2,3])

-------------本文结束感谢您的阅读-------------
0%