matplotlib使用(二)pyplot

matplotlib.pyplot 是命令样式函数的集合

基本用例

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

这里figure()命令是可选的,默认情况下将创建figure(1),默认情况下创建subplot(111.

subplot()中2,1,1制定创建的图行数,列数,和绘图编号。

matplotlib使用(二)pyplot

选择显示图形

您可以使用 clf() 清除当前图形,使用 cla() 清除当前轴。如果你要制作大量的图像,你还需要注意一件事:在用 close() 显式关闭数字之前,数字所需的内存不会完全释放。删除对图的所有引用,和/或使用窗口管理器来杀死屏幕上出现图形的窗口是不够的,因为pyplot会保持内部引用,直到调用close()axes()该命令允许您将位置指定为axes([left, bottom,width,height]),axes将添加新的轴域。轴域显示在画板过程,假定矩形尺寸不变,但刻度归一化到0.0-1.0之间,axes的矩形区域参数在0.0-1.0之间,对应于归一化后的画板位置。
axis()用于轴限制,axis([xmin, xmax, ymin, ymax])。

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(199878)

dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000] / 0.05)
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)] * dt

plt.plot(t, s)
plt.axis([0, 1, 1.1 * np.min(s), 2 * np.max(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Gaussian colored noise')

a = plt.axes([.65, .6, .2, .2], facecolor='k')
n, bins, patches = plt.hist(s, 400, density=True)
plt.title('Probabulity')
plt.xticks([])
plt.yticks([])

a = plt.axes([0.2, 0.6, .2, .2], facecolor='k')
plt.plot(t[:len(r)], r)
plt.title('Impulse response')
plt.xlim(0, 0.2)
plt.xticks([])
plt.yticks([])

plt.show()

 

使用文本

text()命令可用于在任意位置添加文本,所有text()命令返回一个matplotlib.text.Text实例,

可以通过关键字参数,传递给文本函数来自定义属性。

matplotlib在任何文本表达式中接受TeX方程表达式。例如,要在标题中写入表达式σi= 15,您可以编写由美元符号包围的TeX表达式:

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

matplotlib使用(二)pyplot

 注释文本

 

文本的常见用途是注释绘图的某些功能,而annotate()方法提供帮助以使注释变得容易。

在主时钟,有两点需要考虑,由参数xy表示的注释位置和文本xytext的位置。

这两个参数都是(x,y)元组。

在此基本示例中,xy(箭头提示)和xytext位置(文本位置)都在数据坐标中。 可以选择各种其他坐标系 - 有关详细信息,请参阅基本注释高级注释。更多示例可以在Annotating Plots中找到。

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05),
             )

plt.ylim(-2, 2)
plt.show()

matplotlib使用(二)pyplot

Plot的生命周期

关于面向对象的API与Pyplot的说明

Matplotlib由两个接口。第一个是面向对象(OO)接口。在此情况下,利用axes.Axes的示例,以便在figure.Figure

的实例上呈现可视化。

第二种是给予MATLAB并使用基于状态的接口。

注意:通常在pyplot接口上使用面向对象的接口

参考:https://www.matplotlib.org.cn/tutorials/introductory/lifecycle.html