本文所包含的繪圖方式:
極坐标繪圖,函數繪圖,等高線地圖,三維條形圖,三維散點圖,gif 繪圖
1 常用指令
hold on; % 持續繪圖
hold off;
1.1 标注
xlabel('');
ylabel('');
title('');
axis([xmin, xmax, ymin, ymax]);
text(x, y, '') % 圖内文字
% 在指定位置插入文字
% 這個指令會在圖檔視窗顯示後生成一個會随滑鼠移動的十字光标
% 需要移動光标來指定插入文字的位置
gtext('');
1.2 繪制多個子圖
分成
r*c
個子視窗,
p
為子視窗排位(自左向右,自上而下)
subplot(r, c, p)
1.3 圖檔儲存
将目前視窗顯示的圖檔儲存至
'image/i.jpg'
print(gcf, '-djpeg', sprintf('image/%d.jpg',i))
2 二維繪圖
plot(x, y, 'color_point_linestyle', 'linewidth', 2, 'markersize', 12);
'color_point_linestyle'
= 線型 + 線色 + 資料點 (例如
'--r*'
)
- 線型 (-, -., --, : )
- 線色 (r-red, g-green, b-blue, w-white, k-black,i-invisible,y-yellow)
- 資料點 (., o, x, +, *, S, H, D, V, ^)
2.1 極坐标繪圖
x = 0:0.1:2*pi;
r = cos(2*x);
polar(x, r)
2.2 函數繪圖
fplot(fun, lims)
繪制由字元串
fun
指定函數名的函數在 x x x 軸區間為
lims=[xmin, xmax]
的函數圖。例如:
f ( x ) = { x + 1 , x < 1 1 + 1 x , x ≥ 1 f(x)=\begin{cases} x + 1,\;\;x<1\\ 1 +\frac{1}{x},\;\; x\geq 1 \end{cases} f(x)={x+1,x<11+x1,x≥1
2.3 等高線地圖
coun
3 三維繪圖
3.1 三維條形圖
Z = [1, 1, 2, 3;
2, 2, 4, 6;
3, 3, 6, 8];
bar3(Z)
z_{ij}=n
的繪制效果:
在 x-y 坐标系下的
(i,j)
位置繪制一個高
n
的長方柱。例如:
圖 3-1:三維條形圖
3.2 三維散點圖
scatter3(x, y, z, s, c);
% x, y, z 即三維空間坐标
% s 表示散點的大小
% c 表示散點的顔色
示例:
X = 1:0.3:100;
Z = sin(X) + cos(X)';
x = X + zeros(length(X), 1);
x = x(:);
y = x(randperm(length(x)));
z = Z(:);
s = ones(length(z), 1) * 3;
c = [];
for i = 1:length(z)
if z(i) > 1.5, c(i, :) = [1 0 0];
elseif z(i) < 0.5, c(i, :) = [0 1 0];
else, c(i, :) = [0 0 1];
end
end
scatter3(x, y, z, s, c)
圖 3-2:三維散點圖
4 其他
4.1 制作 gif
4.1.1 畫圖的同時生成 gif
p = scatter(randn, randn);
axis([-3, 3, -3, 3]); hold on;
% 将目前圖像存儲至變量 A, map
% getframe 表示擷取目前圖像
[A,map] = rgb2ind(frame2im(getframe),256);
% 将 A, map 存儲為 'image.gif' 圖像的第一幀
imwrite(A,map,'image.gif','LoopCount',65535,'DelayTime',0.1);
for i = 1:10
p = scatter(randn, randn); hold on;
[A,map] = rgb2ind(frame2im(getframe),256);
% 将新的 A, map 存儲為新的一幀并添加至 'image.gif' 中
imwrite(A,map,'image.gif','WriteMode','append','DelayTime',0.1);
pause('on')
pause(0.2)
end
效果圖:
圖 4-1:示例:gif 動圖
4.1.2 将現有的圖檔制作成 gif
令用于生成 gif 的圖檔集包含 10 張名為
'image1.jpg'
…
'image10.jpg'
的圖檔(matlab 圖檔儲存詳見 section 1.3)
for j=1:10
% 擷取圖檔
I = imread(sprintf('image%d.jpg',i));
[A,map] = rgb2ind(I,256);
% 生成 gif 并儲存
if(i == 1)
imwrite(A,map,'image.gif','DelayTime',0.1,'LoopCount',Inf);
else
imwrite(A,map,'image.gif','WriteMode','append','DelayTime',0.1);
end
end