1. figure、subplot、axes、axis的区别
首先官方的示意图:
从图中可以看到Figure是最大的,可以理解成画布或者画板;Axes是Axis的复数,Axis是坐标轴,Axes可以理解为坐标系或者轴域,表示在画板(Figure)上作画的区域;Subplot是子图,可以理解为Axes的高级封装。具体举例如下:
fig = plt.figure() #定义画布
ax1 = fig.add_subplot(211) #子图1
ax2 = fig.add_subplot(212)
#子图表的标题
ax1.set_title('Sub1_Title')
ax2.set_title('Sub2_Title')
#图表总标题
fig.suptitle('Title')
print(type(ax1))
print(type(ax2))
plt.show()
ax1 type: <class ‘matplotlib.axes._subplots.AxesSubplot’>
ax2 type: <class ‘matplotlib.axes._subplots.AxesSubplot’>
fig = plt.figure()
#fig.add_axes([left, bottom, width, height])
ax3 = fig.add_axes([0.1,0.1,0.8,0.8])
ax4 = fig.add_axes([0.72,0.72,0.16,0.16])
print("ax3 type:",type(ax2))
print("ax4 type:",type(ax2))
plt.show()
ax3 type: <class ‘matplotlib.axes._subplots.AxesSubplot’>
ax4 type: <class ‘matplotlib.axes._subplots.AxesSubplot’>
比较段代码和两幅图以及其type类型,不难看出,subplot与axes的类型是一样的,subplot是axes的一种特殊形式(高级分装)其将画板进行了分区编号,在编号区域内绘图;axes在建立时需要给出具体的区域(位置)信息。两者相较,subplot对于需要排列的子图更方便,axes有更高的自由度。
2. matplotlib.pyplot 绘图
x = np.linspace(0,6.48,100)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize=(8,6)) # 定义画布
ax = fig.add_subplot(111) # 定义绘图区域(对象)
ax.plot(x,y,color='blue',marker='o',linestyle='dashed',linewidth=2,markersize=3,label='sin(x)')
ax.plot(x,z,'ro--',linewidth=3,label='cos(x)') # 绘图
props = {'title': 'Title', # 坐标系-标题
'xlabel': 'xlabel', # 坐标系-坐标轴-标签
'xticks': [0, 1.57, 3.14, 4.71, 6.28],
'xticklabels':['one', 'two', 'three', 'four', 'five']} # 坐标系-坐标轴-刻度-标签
ax.set(**props)
ax.legend()
plt.show()