一、Matplotlib Figure概述
画板上垫上画纸才能使用,而且画纸还能叠在一起。这里的。figure等效于画板,而axes/subplot则是画纸。从书包中拿出画板固定两张张画纸的过程,就相当与以下程序:
fig=plt.figure() # 创建figure(拿出画板) ax1=fig.add_subplot(211) #划分2*1区域,在第一个区域固定一张画纸axes ax2=fig.add_subplot(212) #第二张固定另一张画纸 plt.show() # 展示你的成果
之所以把画纸叫做Axes,大概是因为每个画纸都可以建立一个直角坐标系?
那么axes和subplot有区别吗?有的,axes是随意固定在画板的位置,而subplot则是按照均分策略指定区域。下面的效果就可以由axes实现:
注:figure也可以理解为开了多少个绘图的窗口,默认情况下,窗口编号从1开始,你也可以传入一个整型的窗口编号,而不是一个递增的、自动生成的编号。
二、函数式画法和对象式画法是两种作图风格函数式画法,就好像平时我们使用matlab中那样,直接调用函数完成创作过程,而对象式画法,则是通过axes对象完成创作。前者适用于比较简单的绘制,后者则适用于精细的控制。
2.1 函数式画法Matlab中使用函数完成创作过程:
plot([1,2,3,4],[1,4,2,4])
python也提供这种方法:
plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Matplotlib plot.
fig=plt.figure(1) # 取出画板1 ax=fig.subplots() # 画板1上增加画纸 ax.plot([1,2,3,4],[1,4,2,4]) # 开始画画三、Compare with Matlab 3.1 二维图对比
clear close all clc figure(1) x=linspace(0,2,100); plot(x,x,'r','linewidth',1.5) hold on plot(x,x.^2,'--') plot(x,x.^3,'b.') xlabel('x label') ylabel('y label') title('Simple plot in Matlab') lg=legend({'linear','quadratic','cubic'},'Location','best','fontSize',12); title(lg,'Curve Type')
import matplotlib.pyplot as plt import numpy as np plt.close("all") plt.figure(1) x=np.linspace(0,2,100) plt.plot(x,x,color='r',linewidth=1.5) plt.plot(x,x**2,linestyle='--') plt.plot(x,x**3,color='b',linestyle='dotted') plt.xlabel('x label') plt.ylabel('y label') plt.title('Simple plot in Python') lg=plt.legend(['linear','quadratic','cubic'],title='Curve Type') #默认best位置标记 lg.get_title().set_fontweight('semibold')
clear close all clc figure(1) x=linspace(0,2,100); plot3(x,x,sin(x),'r','linewidth',1.5) hold on plot3(x,x.^2,cos(x),'--') plot3(x,x.^3,-cos(x),'b.') xlabel('x label') ylabel('y label') zlabel('z label') title('Simple plot3 in Matlab') lg=legend({'linear','quadratic','cubic'},'Location','best','fontSize',12); title(lg,'Curve Type')
import matplotlib.pyplot as plt import numpy as np plt.close("all") fig=plt.figure(1) ax=plt.axes(projection='3d') x=np.linspace(0,2,100) ax.plot3D(x,x,np.sin(x),color='r',linewidth=1.5) ax.plot3D(x,x**2,np.cos(x),linestyle='--') ax.plot3D(x,x**3,-np.cos(x),color='b',linestyle='dotted') ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_zlabel('z label') ax.set_title('Simple plot3D in Python') lg=ax.legend(['linear','quadratic','cubic'],title='Curve Type') #默认best位置标记 lg.get_title().set_fontweight('semibold')
python只找到了命令行方法:
plt.savefig("C:/Users/xxx/Desktop/resultAna", dpi=750, bbox_inches = 'tight')
matlab在GUI就可设置:导出设置”的设置页面中,选择“渲染->分辨率->600->导出”
小结- 对于二维点(x,y),Matlab和Python区别不大,均可以通过函数式画法完成
- 对于三维点(x,y,z),Matlab和Python画图方式不同。Python在plot或者subplot使用projection='3d’来创建一个axes对象,完成绘制操作;matlab仍可使用函数式完成。