贡献者: addis
Matlab 具有强大的画图功能,这里仅介绍一些基础知识。最常用的画图函数是 plot,例如
>> x = linspace(0, 2*pi, 100); y = sin(x);
>> plot(x, y);
结果如图 1 (左)所示。如果要在该坐标系继续画图,要用 hold on 命令(on 是 hold 的输入变量),否则每用一次 plot,之前画过的图都会被清除。用 hold off 可以重新恢复自动清除。
>> y1 = cos(x);
>> hold on; plot(x, y1);
结果如图 1 (右)所示,注意新增曲线的颜色变化。
plot 函数
如果我们要新建一个画图窗口,用 figure 函数。若要指定画图的颜色,可以添加 figure 的第三个变量,用一个字符表示颜色(red:'r',green:'g',blue:'b',yellow:'y',magenta:'m',cyan:'c',black:'k',white:'w')。例如
>> x2 = cos(x); y2 = sin(x);
>> figure; plot(x2, y2, 'r');
在新增的窗口中,结果如图 2 (左)所示。注意根据窗口尺寸的不同,$x$ 轴和 $y$ 轴的单位长度一般不同,若要使其相同,可以在 plot 后面用 axis equal 命令(其中字符串 equal 是 axis 函数的输入变量),得到图 2 (右)。
若要调整坐标轴的范围,也可用 axis 函数。另外可以在 plot 的第三个变量的字符串中设定曲线的形状,用 xlabel 和 ylabel 函数分别设置 $x$ 轴和 $y$ 轴的文字,用 title 函数设置图片标题
>> plot(x2, y2, '.-r');
>> axis([-1.2, 1.2, -1.2, 1.2]);
>> xlabel('x'); ylabel('y'); title('unit circle');
其中 '.-' 表示带点的连线,点的坐标由 x2 和 y2 决定(另外 '+-' 表示带加号的连线,'o-' 表示带圆圈的连线)。axis 中行矢量中的四个数分别是 $x$ 轴的最小最大值和 $y$ 轴的最小最大值。结果如图 3 (左)所示。
要改变当前窗口中的字号,例如 set(gca, 'FontSize', 14);。其中 gca 获取当前坐标系的对象(get current axis),set 函数设置该对象的 FontSize 属性为 14。在画图窗口菜单中的 View -> Property Inspector 可以查看和修改一张图中任何对象的属性,包括画图窗口的大小和位置。
除了 plot 以外,常用的还有 scatter 函数,用于画散点图。格式与 plot 相似。默认的散点形状是圆圈,但也可以在第三个变量中设置颜色和 '+','x','.' 等形状。例如
>> hold on; scatter(0, 0, 'b');
结果如图 3 (右)所示。
如果直接通过菜单保存图片,会默认使用显示器的分辨率,要按指定的分辨率保存图片例如 exportgraphics(gcf, '文件名.png', 'Resolution', 300)。另外也可以用菜单或者 saveas() 保存为矢量图等格式。另外还有 print 函数也可以保存当前图片窗口:print('图片名', '-dpng', '-r300');。
最后,如果要关闭当前画图窗口,用 close 函数(无输入变量),如果要关闭所有窗口,用 close all 即可。
可以用 axis 对象的 XTick 和 XTickLabel 属性来设置坐标点和显示的文字,例如
figure; plot([1,2,3,2*pi],[1,2,3,5]);
set(gca,'XTick',0:pi/2:2*pi); % gca 用户获取当前的坐标轴对象
set(gca,'XTickLabel',{'0','\pi/2','\pi','3\pi/2','2\pi'});
如果直接用 Figure 窗口中的另存为或者命令 saveas(),那么导出的 pdf 可能有非常宽的白边。这时可以通过 Figure 的 Paper* 属性来控制页面的大小以及 pdf 在页面上的位置。
figure;
plot(1:10, rand(1, 10));
% Set the desired paper size (in inches)
paperWidth = 6;
paperHeight = 4;
set(gcf, 'PaperUnits', 'inches');
set(gcf, 'PaperSize', [paperWidth paperHeight]);
% Set the position and size of the figure on the paper
left = 0.5; % left margin (in inches)
bottom = 0.5; % bottom margin (in inches)
width = paperWidth - 1; % width of the figure (in inches)
height = paperHeight - 1; % height of the figure (in inches)
set(gcf, 'PaperPosition', [left bottom width height]);
% Save the figure as a PDF
saveas(gcf, 'figure.pdf');