Matplotlib有两种主要的应用接口(APIs)或使用库的风格:
- 一个显式的“坐标轴”接口,使用Figure或Axes对象的方法来创建其他绘图元素,并逐步构建可视化内容。这也被称为“面向对象”的接口。
- 一个隐式的“pyplot”接口,它会跟踪最后创建的Figure和Axes,并将Artist添加到它认为用户想要的对象中。
此外,一些下游库(如pandas和xarray)在其数据类上直接实现了plot方法,从而使用户可以调用data.plot()。网络上的代码可能运用其中的一个接口,或者多种接口。
显示接口
显示接口需要指明figure和axes,然后通过figure和axes调整坐标轴,标题等。
import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,2*np.pi,1000)
x=16*(np.sin(t))**3
y=13*np.cos(t)-5*np.cos(2*t)-2*np.cos(3*t)-np.cos(4*t)
random_list_r=np.random.uniform(0,1,len(t))
random_list_theta=np.random.uniform(0,2*np.pi,len(t))
R=np.sqrt((x**2+y**2)*random_list_r)
x_r=R*np.cos(random_list_theta)
y_r=R*np.sin(random_list_theta)
fig, ax = plt.subplots(figsize=(8,8))
ax.plot(x,y,color='red',linewidth=5)
ax.scatter(x_r,y_r,color='pink',marker='x')
ax.set_aspect('equal')
ax. Axis('off')
plt.show()
隐式接口
隐式接口通过pyplot来实现,可以使用 gcf 获取当前图形的引用,使用 gca 获取当前坐标轴的引用。
import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,2*np.pi,1000)
x=16*(np.sin(t))**3
y=13*np.cos(t)-5*np.cos(2*t)-2*np.cos(3*t)-np.cos(4*t)
random_list_r=np.random.uniform(0,1,len(t))
random_list_theta=np.random.uniform(0,2*np.pi,len(t))
R=np.sqrt((x**2+y**2)*random_list_r)
x_r=R*np.cos(random_list_theta)
y_r=R*np.sin(random_list_theta)
plt.plot(x,y,color='red',linewidth=5)
plt.scatter(x_r,y_r,marker='x',color='pink')
plt.axis('equal')
plt.axis('off')
plt.show()
之前没了解感觉看到绘图代码的不同写法很迷惑,所以在这里记一下。更细致的内容待以后补充。