Matlab繪圖高級部分


圖形是呈現數據的一種直觀方式,在用Matlab進行數據處理和計算后,我們一般都會以圖形的形式將結果呈現出來。尤其在論文的撰寫中,優雅的圖形無疑會為文章加分。本篇文章非完全原創,我的工作就是把見到的Matlab繪圖代碼收集起來重新跑一遍,修改局部錯誤,然后將所有的圖貼上來供大家參考。大家可以先看圖,有看中的可以直接把代碼Copy過去改成自己想要的。


%% 直方圖圖的繪制 %直方圖有兩種圖型:垂直直方圖和水平直方圖。而每種圖型又有兩種表現模式:累計式:分組式。 figure; z=[3,5,2,4,1;3,4,5,2,1;5,4,3,2,5]; % 各因素的相對貢獻份額 colormap(cool);% 控制圖的用色 subplot(2,3,1); bar(z);%二維分組式直方圖,默認的為'group' title('2D default'); subplot(2,3,2); bar3(z);%三維的分組式直方圖 title('3D default'); subplot(2,3,3); barh(z,1);%分組式水平直方圖,寬度設置為1 title('vert width=1'); subplot(2,3,4); bar(z,'stack');%累計式直方圖,例如:1,1+2,1+2+3構成了第一個bar title('stack') subplot(2,3,5); bar3h(z,0.5,'stacked');%三維累計式水平直方圖 title('vert width=1 stack'); subplot(2,3,6); bar3(z,0.8,'grouped');%對相關數據的顏色進行分組,默認的位'group' title('width=0.8 grouped');

%% =========柱狀圖的進階==========
figure;
y=[300 311;390 425; 312 321; 250 185; 550 535; 420 432; 410 520;];
subplot(1,3,1);
b=bar(y);
grid on;
set(gca,'XTickLabel',{'0','1','2','3','4','5','6'})
legend('算法1','算法2');
xlabel('x axis');
ylabel('y axis');
%使僅有的一組柱狀圖呈現不同顏色,默認的位相同顏色
data = [1.0, 1.0, 0.565, 0.508, 0.481, 0.745];
subplot(1,3,2);
b = bar(data);
ch = get(b,'children');
set(ch,'FaceVertexCData',[4;2;3;1;5;6]);%使用Indexed形式指定每組bar的顏色
set(gca,'XTickLabel',{'C0','C1','C2','C3','C4','C5'})
axis([0 7 0.0 1.0]);
ylabel('micro F-measure');
%使每個bar顏色不同,默認的是每個元素在不同組的顏色相同
data = [3, 7, 5, 2;4, 3, 2, 9;6, 6, 1, 4];
subplot(1,3,3);
b = bar(data);
ch = get(b,'children');
set(ch{1},'FaceVertexCData',[1;2;3]);%設置第一個元素在不同組的顏色
set(ch{2},'FaceVertexCData',[1;2;3]);%設置第二個元素在不同組的顏色
set(ch{3},'FaceVertexCData',[1;2;3]);
set(ch{4},'FaceVertexCData',[1;2;3]);

%% 彩色柱狀圖
%用到的數據
n = 8;
Z = rand(n,1);
figure;
%默認圖片
subplot(1,3,1);
bar(Z);
%簡單的作圖
% 這個圖根據數據列中值的大小着色。每列中的值越大,顏色越突出
subplot(1,3,2);
h=bar(Z);
colormap(summer(n));
ch = get(h,'Children');
fvd = get(ch,'Faces');%針對矩陣時,只能用fvd=get(ch{col},'Faces'),下同
fvcd = get(ch,'FaceVertexCData');
[~, izs] = sortrows(Z,1);
for i = 1:n
    row = izs(i);
    fvcd(fvd(row,:)) = i;
end
set(ch,'FaceVertexCData',fvcd)
%圖片會以漸變的方式着色,效果非常不錯
subplot(1,3,3);
h=bar(Z);
ch = get(h,'Children');
fvd = get(ch,'Faces');
fvcd = get(ch,'FaceVertexCData');
[zs, izs] = sortrows(Z,1);
k = 128; % 准備生成128 *3 行的colormap
colormap(summer(k)); % 這樣會產生一個128 * 3的矩陣,分別代表[R G B]的值
% 檢視數據
whos ch fvd fvcd zs izs
%   Name       Size            Bytes  Class     Attributes
%
%   ch         1x1                 8  double
%   fvcd      66x1               528  double
%   fvd       13x4               416  double
%   izs       13x1               104  double
%   zs        13x1               104  double
%
shading interp % Needed to graduate colors
for i = 1:n
    color = floor(k*i/n); % 這里用取整函數獲得color在colormap中行
    row = izs(i); % Look up actual row # in data
    fvcd(fvd(row,1)) = 1; % Color base vertices 1st index
    fvcd(fvd(row,4)) = 1;
    fvcd(fvd(row,2)) = color; % Assign top vertices color
    fvcd(fvd(row,3)) = color;
end
set(ch,'FaceVertexCData', fvcd); % Apply the vertex coloring
set(ch,'EdgeColor','k');

%% 繪制統計直方圖
%hist(y):如果y是向量,則把其中元素放入10個條目中,且返回每條中的元素的個數;如果y為矩陣,則分別對每列進行處理,顯示多組條形。
%[n,xout]=hist(y,x):非遞減向量x的指定bin的中心。向量xout包含頻率計數與條目的位置。
x=-10:.1:10;
y1=randn(2008,1);
y2=randn(2008,3);
figure;
colormap(winter);
subplot(2,2,1);
hist(y1);%把其中元素放入10個條目中
title('y1為向量,default,n=10');
subplot(2,2,2);
hist(y2);%分別對每列進行處理,顯示多組條形
title('y2為矩陣');
subplot(2,2,3);
hist(y1,x);%用戶也可以使用[n,xout]=hist(y1,x);bar(xout,n)繪制條形直方圖
title('向量x指定條目');
subplot(2,2,4);
hist(y2,1000);%第二個參數為標量時指定bin的數目
title('nbins=1000');

%% ========均值方差直方圖========
a=[8 9 10 7 8 9];%mean
b=[1 1 1 1 1 1];%std
figure();
h=bar(a);
ch=get(h,'children');
set(ch,'FaceVertexCData',[4;2;3;1;5;6]);%使用Indexed形式指定每組bar的顏色
hold on;
errorbar(a,b,'k','LineStyle','none');

%% =======散點圖scatter , scatter3 , plotmatrix======
%scatter3(X,Y,Z,S,C):在由向量X、Y和Z指定的位置顯示大小和顏色分別由S和C決定的離散點
figure;
[x,y,z] = sphere(16);
X = [x(:)*.5 x(:)*.75 x(:)];
Y = [y(:)*.5 y(:)*.75 y(:)];
Z = [z(:)*.5 z(:)*.75 z(:)];
S = repmat([10 2 5]*10,numel(x),1);
C = repmat([1 2 3],numel(x),1);
subplot(1,2,1);
scatter(X(:),Y(:),S(:),C(:));
title('scatter');
subplot(1,2,2);
scatter3(X(:),Y(:),Z(:),S(:),C(:),'filled'), view(-60,60);
title('scatter3');
%plotmatrix(X,Y)繪出X(p*M)與Y(p*N)的列組成的散度圖(N,M)
figure;
X=randn(100,2);Y=randn(100,2); 
subplot(1,3,1),plotmatrix(X);%等價於plotmatrix(X,X),除了對角上的圖為X每一列的直方圖hist(X(:,col))
title('plotmatrix(X)');
subplot(1,3,2),plotmatrix(X,X);
title('plotmatrix(X,X)');
subplot(1,3,3),plotmatrix(X,Y);
title('plotmatrix(X,Y)');

%% =========繪制區域圖===========
%區域圖特點是:在圖上繪制多條曲線時,每條曲線(除第一條外)都是把“前”條曲線作基線,再取值繪制而成。因此,該指令所畫的圖形,能醒目地反映各因素對最終結果的貢獻份額。
figure;
x=1:2:9;% 注意:自變量要單調變化
y=magic(5);% 各因素的相對貢獻份額,每一列相當於一個因素
colormap(spring);% 控制圖的用色
area(x,y,4);%area(y)則以列下標作為自變量,第三個參數為基准線(默認為0)
set(gca,'layer','top');%圖層設置為top層,顯示網格
title('basevalue=4');
legend(' 因素 A',' 因素 B',' 因素 C','因素D','因素E');
grid on;

%% =========繪制餅狀圖=========
%餅圖指令pie和pie3用來表示各元素占總和的百分數。該指令第二個參數為與第一參數等長的 0-1
%向量,1使對應扇塊突出。第三個參數指定個扇區的label
figure;
colormap(summer);% 控制圖的用色
x=[16 17 21 25 21];
subplot(1,2,1);
pie(x,[0 0 0 0 1],{'0-10歲兒童','10-20歲兒童','20-35歲青年','35-55歲中年','55歲以上老年'});
subplot(1,2,2);
pie3(x,[0 0 0 0 1],{'0-10歲兒童','10-20歲兒童','20-35歲青年','35-55歲中年','55歲以上老年'});

%% 繪制填色多邊形。若每列的首尾元素不重合,則將默認把最后一點與第一點相連,強行使多邊形封閉。
%fill和fill3用於繪制填色多邊形
%fill(X1,Y1,C1,X2,Y2,C2,...)
%fill3(X1,Y1,Z1,C1,X2,Y2,Z2,C2,...)
%參數1和2為等長向量時,多邊形的節點數由項鏈長度決定;而當其為矩陣時,每一列對應一個多邊形
%參數3為顏色(用顏色字符r/g/b/c或[r g b]表示)
figure;
colormap(autumn);% 控制圖的用色
n=10; % 多邊形的邊數
dt=2*pi/n;t=0:dt:2*pi;
t=[t,t(1)]; %fill 指令要求數據向量的首位重合,使圖形封閉。
x=sin(t);y=cos(t);
subplot(1,2,1);
fill(x,y,[1 1 0]);axis off % 畫填色多邊形,隱去坐標軸。
X=[0.5 0.5 0.5 0.5;0.5 0.5 0.5 0.5;0 1 1 0]; 
Y=[0.5 0.5 0.5 0.5;0.5 0.5 0.5 0.5;0 0 1 1];
Z=[1 1 1 1;0 0 0 0;0 0 0 0];
C=[1 0 0 1;0 1 0 1;0 0 1 0];
subplot(1,2,2);
fill3(X,Y,Z,C);
view([-10 55]);
xlabel('x'),ylabel('y');box on;grid on;

 

%% =======繪制離散數據桿狀圖===========
%stem和stem3函數用於繪制二維或三維的離散數據桿狀圖
%stem(Y)可以理解成繪制離散點的plot(y)函數
%stem(X,Y)可以理解成繪制離散點的plot(x,y)函數
%stem(...,'filled')改變數據點顯示的空、實狀態。
%stem(...,'LINESPEC')Linespec代表直線屬性設置參量。
x=1:.1:10;
y=exp(x.*sin(x));
figure;
subplot(1,3,1);
plot(x,y,'.-r');
title('plot(x,y)');
subplot(1,3,2);
stem(x,y,'b');
subplot(1,3,3);
stem(x,y,':g','fill');
%繪制三維離散桿狀圖
th=(0:127)/128*2*pi;% 角度采樣點
x=cos(th);
y=sin(th);
f=abs(fft(ones(10,1),128)); %對離散方波進行 FFT 變換,並取幅值
stem3(x,y,f','cd','fill');%繪制圖形
view([-65 30]);
xlabel('Real'); %圖形標注
ylabel('Imaginary');
zlabel('Amplitude');
title('FFT example');

 

%% =======繪制方向和速度矢量圖=======
%compass-繪制羅盤圖
%feather-繪制羽毛圖
%quiver-繪制二維箭頭圖
%quiver3-繪制三維箭頭圖

%繪制羅盤圖
figure;
wdir=[45 90 90 45 360 335 360 270 335 270 335 335];
knots=[6 6 8 6 3 9 6 8 9 10 14 12];
rdir=wdir*pi/180;
[x,y]=pol2cart(rdir,knots);% 極坐標轉化為直角坐標
compass(x,y);
title('風向和風力')
%繪制羽毛圖
figure;
alpha=90:-10:0;
r=ones(size(alpha));
m=alpha*pi/180;
n=r*10;
[u,v]=pol2cart(m,n);% 極坐標轉化為直角坐標
feather(u,v);
title('羽毛圖')
%羅盤圖和羽毛圖的比較
figure;
t=-pi/2:pi/12:pi/2; % 在 區間,每 取一點。
r=ones(size(t)); % 單位半徑
[x,y]=pol2cart(t,r); % 極坐標轉化為直角坐標
subplot(1,2,1),compass(x,y),title('Compass')
subplot(1,2,2),feather(x,y),title('Feather')
%繪制箭頭圖
figure;
[x,y] = meshgrid(-2:.2:2,-1:.15:1);
z = x .* exp(-x.^2 - y.^2); 
[px,py] = gradient(z,.2,.15);
subplot(1,2,1);
contour(x,y,z), hold on
quiver(x,y,px,py), hold off, axis image
title('quiver示例');
[x,y,z]=peaks(15);
[nx,ny,nz]=surfnorm(x,y,z);%surfnorm求平面的法向量
subplot(1,2,2)
surf(x,y,z);
hold on;
quiver3(x,y,z,nx,ny,nz);
title('quiver3示例');

 

%% ==========輪廓線圖的繪制==========
%clabel-利用輪廓矩陣生成標簽並在當前圖形中顯示
%contour-利用矩陣所給的值生成二維輪廓線
%contour3-利用矩陣所給的值生成三維輪廓線
%contourf-顯示二維輪廓圖並用色彩填充個輪廓線的間隙
%contourc-計算被其他輪廓函數占用的輪廓矩陣的低層函數
[x,y,z]=peaks;
n=15;% 等高線分級數
figure;
subplot(1,3,1);
h=contour(x,y,z,n);%繪制20條等高線
clabel(h);%當前圖形中顯示標簽,標簽前有'+'號且標簽會根據輪廓線旋轉,每條輪廓線僅有一個標簽
title('simple contour,n=20');
subplot(1,3,2);
z=peaks;
[c,h]=contour(z,n);%繪制15條等高線
clabel(c,h);%標簽前無'+'號,每天輪廓線可能有多個標簽
title('調用clabel函數標注輪廓圖')
subplot(1,3,3);
z=peaks;
[c,h]=contourf(z,n);
clabel(c,h,'FontSize',15,'Color','r','Rotation',0);%自定義標簽
colorbar;
title('使用自定義標注並彩色填充輪廓線的間隙');

 

%% ========= Voronoi圖和三角剖分========
%用Voronoi多邊形勾畫每個點的最近鄰范圍。Voronoi多邊形在計算幾何、模式識別中有重要應用。三角形頂點所在多邊形的三條公共邊是剖分三角形邊的垂直平分線。
n=30;
A=rand(n,1)-0.5;
B=rand(n,1)-0.5; % 產生 30 個隨機點
T=delaunay(A,B); % 求相鄰三點組
T=[T T(:,1)]; %為使三點剖分三角形封閉而采取的措施
voronoi(A,B) % 畫 Voronoi 圖
hold on;axis square
fill(A(T(10,:)),B(T(10,:)),'y'); % 畫一個剖分三角形
voronoi(A,B) % 重畫 Voronoi 圖,避免線被覆蓋
title('Voronoi圖和三角剖分');

 

%% =========三角網線和三角曲面圖========
figure;
X=6*pi*(rand(20,10)-0.5);Y=6*pi*(rand(20,10)-0.5); 
R=sqrt(X.^2+Y.^2)+eps;Z=sin(R)./R;
tri=delaunay(X,Y); % 進行三角剖分
subplot(1,2,1),trimesh(tri,X,Y,Z);
title('三角網線');
subplot(1,2,2),trisurf(tri,X,Y,Z);
title('三角曲面圖');
colormap(copper);brighten(0.5) % 增強亮度

 

%% ============彩帶圖ribbon========
%ribbon(X,Y,WIDTH)和plot(X,Y)一樣的,只不過每一列在三維中以分開的ribbon繪制
figure;
x=0:pi/100:2*pi;
x=repmat(x',1,10);
y=sin(x);
ribbon(x,y,0.4);% 畫彩帶圖
% 至此彩帶圖已經生成。以下指令都是為了使圖形效果更好、標識更清楚而用。
view([150,50]),shading interp,colormap(hot)% 設置視角、明暗、色圖
light,lighting phong,box on % 設置光源、照射模式、坐標框

 

%% ==========在特殊坐標系中繪制特殊圖形。=======
%利用polar函數在極坐標系中繪制圖形
figure;
theta=0:.1:pi;
rho1=sin(theta);
rho2=cos(theta);
subplot(1,3,1);
polar(theta,rho1,'.-r');
hold on;
polar(theta,rho2,'--g');
title('極坐標系中繪圖');
%另外一種和極坐標有關系的坐標系就是柱坐標系了
theta=0:pi/100:3*pi;
rho=sin(theta)+cos(theta);
[t,r]=meshgrid(theta,rho);
z=r.*t;
subplot(1,3,2);
[x,y,z]=pol2cart(t,r,z);%極坐標系向柱坐標系轉化
mesh(x,y,z);%柱坐標系中進行繪圖
title('柱坐標系中繪圖');
view([-65 30]);
%將球坐標系轉換為柱面坐標系
subplot(1,3,3);
delta=pi/100;
theta=0:delta:pi; % theta is zenith angle
phi=0:delta:pi; % phi is azimuth angle
[t p]=meshgrid(theta,phi);
r=ones(size(t));
[x,y,z]=sph2cart(t,p,r);%球坐標向柱坐標轉化
mesh(x,y,z);%球坐標系中進行繪圖
title('球坐標系中繪圖');

 

%% ======四維表現========
%用色彩表現函數的特征
%當三維網線圖、曲面圖的第四個輸入宗量取一些特殊矩陣時,色彩就能表現或加強函數的某特征,如梯度、曲率、方向導數等。
x=3*pi*(-1:1/15:1);y=x;[X,Y]=meshgrid(x,y); 
R=sqrt(X.^2+Y.^2)+eps;Z=sin(R)./R;
[dzdx,dzdy]=gradient(Z);dzdr=sqrt(dzdx.^2+dzdy.^2); % 計算對 r 的全導數
dz2=del2(Z); % 計算曲率
figure;
subplot(1,2,1),surf(X,Y,Z),title('No. 1 surf(X,Y,Z)');
shading faceted,colorbar( 'horiz') ,brighten(0.2);
subplot(1,2,2),surf(X,Y,Z,R),title('No. 2 surf(X,Y,Z,R)');
shading faceted;colorbar( 'horiz');
%色彩分別表現函數的高度和半徑特征
figure;
subplot(1,2,1),surf(X,Y,Z,dzdx) ;
shading faceted;brighten(0.1);colorbar( 'horiz');
title('No. 3 surf(X,Y,Z,dzdx)');
subplot(1,2,2),surf(X,Y,Z,dzdy);
shading faceted;colorbar( 'horiz');
title('No. 4 surf(X,Y,Z,dzdy)');
%色彩分別表現函數的 x 方向和 y 方向導數特征
figure;
subplot(1,2,1),surf(X,Y,Z,abs(dzdr)) ;
shading faceted;brighten(0.6);colorbar( 'horiz');
title('No. 5 surf(X,Y,Z,abs(dzdr))');
subplot(1,2,2),surf(X,Y,Z,abs(dz2));
shading faceted;colorbar( 'horiz');
title('No. 6 surf(X,Y,Z,abs(dz2))');

 

%% ======切片圖和切片等位線圖=======
%利用 slice 和 contourslice 表現 MATLAB 提供的無限大水體中水下射流速度數據 flow 。 flow 是一組定義在三維空間上的函數數據。
%在本例中,從圖中的色標尺可知,深紅色表示“正速度”(向圖的左方),深藍表示“負速度”(向圖的右方)。
% 以下指令用切面上的色彩表現射流速度
[X,Y,Z,V]=flow; % 取 4 個 的射流數據矩陣, V 是射流速度。
x1=min(min(min(X)));x2=max(max(max(X))); % 取 x 坐標上下限
y1=min(min(min(Y)));y2=max(max(max(Y))); % 取 y 坐標上下限
z1=min(min(min(Z)));z2=max(max(max(Z))); % 取 z 坐標上下限
sx=linspace(x1+1.2,x2,5); % 確定 5 個垂直 x 軸的切面坐標
sy=0; % 在 y=0 處,取垂直 y 軸的切面
sz=0; % 在 z=0 處,取垂直 z 軸的切面
figure;
slice(X,Y,Z,V,sx,sy,sz); % 畫切片圖
view([-12,30]);shading interp;colormap jet;axis off;colorbar;
% 以下指令用等位線表現射流速度
v1=min(min(min(V)));v2=max(max(max(V))); % 射流速度上下限
cv=linspace(v1,v2,15); % 在射流上下限之間取 15 條等位線
figure;
contourslice(X,Y,Z,V,sx,sy,sz,cv);view([-12,30]);
colormap jet;colorbar;box on;

下面兩段程序均不便上圖,自己拿到Matlab里面運行一下看效果吧。

%% =======動態圖形=========
%簡單二維示例-彗星狀軌跡圖
figure;
n=10;t=n*pi*(0:0.0005:1);x=sin(t);y=cos(t);
plot(x,y,'g');axis square;hold on
comet(x,y,0.01);hold off
%衛星返回地球的運動軌線示意
figure;
R0=1; % 以地球半徑為一個單位
a=12*R0;b=9*R0;T0=2*pi; %T0 是軌道周期
T=5*T0;dt=pi/100;t=[0:dt:T]';
f=sqrt(a^2-b^2); % 地球與另一焦點的距離
th=12.5*pi/180; % 衛星軌道與 x-y 平面的傾角
E=exp(-t/20); % 軌道收縮率
x=E.*(a*cos(t)-f);y=E.*(b*cos(th)*sin(t));z=E.*(b*sin(th)*sin(t));
plot3(x,y,z,'g') % 畫全程軌線
[X,Y,Z]=sphere(30);X=R0*X;Y=R0*Y;Z=R0*Z; % 獲得單位球坐標
grid on,hold on,surf(X,Y,Z),shading interp % 畫地球
x1=-18*R0;x2=6*R0;y1=-12*R0;y2=12*R0;z1=-6*R0;z2=6*R0;
axis([x1 x2 y1 y2 z1 z2]) % 確定坐標范圍
view([117 37]),comet3(x,y,z,0.02),hold off % 設視角、畫運動軌線
%色彩變幻‘在 256 色情況下,才可被正確執行.圖片刷新可能會卡,單獨執行spinmap可查看到效果
figure;
peaks;
spinmap;
 %% =======影片動畫 =======
%三維圖形的影片動畫
figure;
shg,x=3*pi*(-1:0.05:1);y=x;[X,Y]=meshgrid(x,y);
R=sqrt(X.^2+Y.^2)+eps; Z=sin(R)./R;
h=surf(X,Y,Z);colormap(cool);axis off
n=12;mmm=moviein(n); %預設畫面矩陣。新版完全可以取消此指令 。
for i=1:n
rotate(h,[0 0 1],25); %是圖形繞 z 軸旋轉 25 度 / 每次
mmm(:,i)=getframe; %捕獲畫面。新版改為 mmm(i)=getframe 。
end
movie(mmm,5,10) %以每秒10幀速度,重復播放5次


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM