# preface

[Guo Yanfu of National Taiwan University] PPT link: https://pan.baidu.com/s/1VXdy3HCBPexMK0csyehiZA Extraction code: 2io1
matlab official help document: https://ww2.mathworks.cn/help/

Select various types of diagrams according to your needs. # 1, Advanced 2D drawing

## 1. Logarithmic diagram

• Logspace (- 1,1100): x 1 0 − 1 10^{-1} 10−1~ 1 0 1 10^{1} 100 variables between 101
• semilogx(x,y): the X axis is a logarithmic coordinate system, that is, a plot is created using the logarithmic scale of the X axis based on 10 and the linear scale of the Y axis.
• semilogy(x,y): the Y axis is a logarithmic coordinate system, that is, a plot is created using the logarithmic scale of the Y axis based on 10 and the linear scale of the X axis.
• loglog(x, y): both X and Y coordinates are logarithmic coordinate systems

eg.

```x = logspace(-1,1,100);
y = x.^2;
subplot(2,2,1);
plot(x,y);
title('Plot');
subplot(2,2,2);
semilogx(x,y);
title('Semilogx');
subplot(2,2,3);
semilogy(x,y);
title('Semilogy');
subplot(2,2,4);
loglog(x, y);
title('Loglog');
``` Grid:

```set(gca,'XGrid','on');
``` ## 2. Double y-axis in Figure 1

• Plot () draws two curves with different vertical axes on the left and right.
y = a e − b x s i n ( c x ) y=ae^{-bx}sin(cx) y=ae−bxsin(cx) • [AX,H1,H2] = plotyy(): the handle returned to AX two coordinate areas (Axes). AX(1) represents the handle of the left coordinate area and AX(2) represents the handle of the right coordinate area. Returns the handle of the Line object in each plot of H1 and H2

eg.

```x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[AX,H1,H2] = plotyy(x,y1,x,y2);
set(get(AX(1),'Ylabel'),'String','LeftY-axis')
set(get(AX(2),'Ylabel'),'String','RightY-axis')
title('Labeling plotyy');
set(H1,'LineStyle','--');
set(H2,'LineStyle',':');
``` • Use yyaxis() to activate the left and right coordinate axes and set them respectively.
```x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);

yyaxis left;
p1 = plot(x,y1);
ylabel('LeftY-axis')
title('Labeling plotyy');
p1.LineStyle = '--';

yyaxis right;
p2 = plot(x,y2);
ylabel('RightY-axis')
p2.LineStyle = ':';
```
• Clear left curve command:
```yyaxis left;
cla;
``` ## 3. Histogram

• Histogram to see the overall situation
• hist(y) defaults to ten equally spaced intervals and returns the number of Y elements in each range as a line vector.
• hist(y,x) is divided into x equally spaced intervals.

eg.

```y = randn(1,1000);
subplot(2,1,1);
hist(y,10);
title('Bins = 10');
subplot(2,1,2);
hist(y,50);
title('Bins = 50');
``` ## 4. Bar chart

• Bar chart to see individual situations
• bar() creates a bar graph.
If y is a vector, each vector in Y corresponds to a bar, as shown in Figure 1;
If y is a matrix, it is grouped according to the rows in Y, as shown in Fig. 2;
• (3) draw 3D diagram

eg.

```x = [1 2 5 4 8];
y = [x;1:5];
subplot(1,3,1);
bar(x);
title('A bargraphof vector x');
subplot(1,3,2);
bar(y);
title('A bargraphof vector y');
subplot(1,3,3);
bar3(y);
title('A 3D bargraph');
``` • bar(y,'stacked') is a stacked bar chart to show how much the sum is.
• barh(y) is a horizontal bar graph.

eg.

```x = [1 2 5 4 8];
y = [x;1:5];
subplot(1,2,1);
bar(y,'stacked');
title('Stacked');
subplot(1,2,2);
barh(y);
title('Horizontal');
``` practice

Exercise:stack the horizontal bar chart

```x = [1 2 5 4 8];
y = [x;1:5];
subplot(1,2,1);
bar(y,'stacked');
title('Vertical stacking diagram');

subplot(1,2,2);
barh(y,'stacked');
title('Horizontal stacking diagram');
``` ## 5. Pie chart

• pie(a) use the data in a to draw the pie chart. If sum(a) ≥ 0, draw it in proportion; sum(a) < 1, only part of the pie chart is drawn to scale.
• Pie (a, expand) sets the corresponding expand element to 1 to offset this part, as shown in Figure 2.
• pie3() draws a 3D pie chart, as shown in Figure 3.
• Pie (x, {taxes', 'expenses',' profit '}) uses {} to set labels.

eg.

```a = [10 5 20 30];
subplot(1,3,1);
pie(a);
subplot(1,3,2);
pie(a, [0,0,0,1]);
subplot(1,3,3);
pie3(a, [0,0,0,1]);
``` practice

Exercise: separate all the pieces in the pie chart

```a = [10 5 20 30];
pie(a, [1,1,1,1]);
``` ## 6. Polar diagram

• polar(theta,r), where theta is the polar angle and r is the radius
• linspace is used to generate linear spacing vectors:
linspace(x1,x2) returns a row vector containing 100 equally spaced points between X1 and x2.
linspace(x1,x2,n) generates n points. The spacing between these points is (x2-x1)/(n-1).
• ones() Create an array of all 1
• Recommended in the latest version: polarplot()

eg.

```x = 1:100;theta = x/10;
r = log10(x);
subplot(1,4,1);
polar(theta,r);
theta = linspace(0, 2*pi);
r = cos(4*theta);
subplot(1,4,2);
polar(theta, r);
theta = linspace(0, 2*pi, 6);
r = ones(1,length(theta));
subplot(1,4,3);
polar(theta,r);
theta = linspace(0, 2*pi);
r = 1-sin(theta);
subplot(1,4,4);
polar(theta , r);
``` practice

Exercise: plot a hexagon on a polar chart

```theta = linspace(0, 2*pi,7);
r = ones(1,length(theta));
polar(theta,r);
``` ## 7. Ladder diagram and sampling diagram

stairs()Stairs : connect points using segments parallel to the x and y axes
stem()Discrete sequence diagram : connect the points vertically to the x-axis

eg.

```x = linspace(0, 4*pi, 40);
y = sin(x);
subplot(1,2,1);
stairs(y);
subplot(1,2,2);
stem(y);
``` practice ```t = linspace(0,10,1000);
f = sin(pi*(t.^2/4));
plot(t,f);
hold on;
x = linspace(0,10,50);
y = sin(pi*(x.^2/4));
stem(x,y);
``` ## 8. Box line diagram and error line diagram

eg.

```load carsmall
boxplot(MPG, Origin);
```
```x=0:pi/10:pi; y=sin(x);
e=std(y)*ones(size(x));
errorbar(x,y,e)
``` ## 9. Filling diagram

• Using plot() is to draw lines, while using fill() is to draw lines and paint colors
• fill(x,y,ColorSpec) fills the 2D polygon specified by X and Y (color specified by ColorSpec)
As shown in the figure below, fill(x,y,'r') draws a polygon and fills it with red.
• axis square off is a combination of axis square and axis off.
• text() Add text information

eg.

```t =(1:2:15)'*pi/8;
x = sin(t);
y = cos(t);
fill(x,y,'r');
axis square off;
text(0,0,'STOP','Color', 'w','FontSize', 80, ...
'FontWeight','bold','HorizontalAlignment','center');
``` practice ```t =(0:4)*pi/2;
x = sin(t);
y = cos(t);
fill(x,y,'y');
axis square off;
text(0,0,'WAIT','Color', 'k','FontSize', 70, ...
'FontWeight','bold','HorizontalAlignment','center');
``` • To set the border of the filled polygon, you need to get its handle, and then set the parameters next
```t =(0:4)*pi/2;
x = sin(t);
y = cos(t);
h = fill(x,y,'y');
h.LineWidth = 5;
axis square off;
text(0,0,'WAIT','Color', 'k','FontSize', 70, ...
'FontWeight','bold','HorizontalAlignment','center');
``` # 2, Color matching

## 1.RGB

• [R G B]: a color standard, which obtains various colors through the superposition of red, green and blue. The number between 0 and 255 (decimal system) is usually used to represent the proportion of each component.

• For example, the white [255 255] hexadecimal is [FF FF FF], which is recorded as #FFFFFF • G. The three vectors S and B need to be transposed first and then connected in series, because bar() divides each row of the matrix into a group and draws bars respectively;

eg.

```G = [46 38 29 24 13];
S = [29 27 17 26 8];
B = [29 23 19 32 7];
h = bar(1:5, [G' S' B']);
title('Medal count for top 5 countries in 2012 Olympics');
ylabel('Number of medals');
xlabel('Country');
legend('Gold', 'Silver', 'Bronze')
``` practice

Change color

• During color setting, matlab does not seem to support the use of an array of 0 ~ 255 to represent [R G B]. Divide each item of the array of 0 ~ 255 by 255 and convert it to 0 ~ 1.
```G = [46 38 29 24 13];
S = [29 27 17 26 8];
B = [29 23 19 32 7];
% Specify string tag x axis
str=categorical({'USA','CHN','GBR','RUS','KOR'});
% While drawing, draw each bar handle Bestow h，And will FaceColor Property is set to flat
h = bar(str, [G' S' B'],'FaceColor','flat');

for i=1:size(G',1)      % Set the first bar of each group to gold
h(1).CData(i,:)=[1,0.843,0];
end
for i=1:size(G',1)      % Set the second bar of each group to silver
h(2).CData(i,:)=[0.753 0.753 0.753];
end
for i=1:size(G',1)      % Set the third bar of each group to copper
h(3).CData(i,:)=[.545,.27,.0745];
end
title('Medal count for top 5 countries in 2012 Olympics');
ylabel('Number of medals'); xlabel('Country');
legend('Gold', 'Silver', 'Bronze')  % Add legend
``` ## 2. Data visualization as image

• The meshgrid function is used to generate the grid matrix
• surf() : draw a surface
• box on display axis outline
```[x, y] = meshgrid(-3:.2:3,-3:.2:3);
z = x.^2 + x.*y + y.^2;
surf( x, y, z);
box on;
set(gca,'FontSize', 16);
zlabel('z');
xlim([-4 4]);
xlabel('x');
ylim([-4 4]);
ylabel('y');
``` • imagesc(z) converts the values of the elements in the matrix Z into different colors according to the size, and dyes them with this color at the corresponding position of the coordinate axis
```imagesc(z);
axis square;
xlabel('x');
ylabel('y');
``` • Use the colorbar command to call up the color bar as shown in the figure;
• Use colormap() to change the color of the visual image; • The parameters of colormap() are as follows: practice ```x = [1:10; 3:12; 5:14];
imagesc(x);
colorbar;
map = zeros(256,3);
map(:,2) = (0:255)/255;
colormap(map);
``` # 3, 3D drawing

## 1. 2D VS 3D

```x=0:0.1:2*pi;
plot(x,sin(x));
```

## 2. 3D point or line diagram

• plot3 (X, Y, Z) draws coordinates in 3-D space.

• To draw a set of coordinates connected by segments, specify XYZ as a vector of the same length.

To draw multiple sets of coordinates on the same set of axes, specify at least XYZ, at least one of which is a matrix, and the other coordinates are vectors.

```x=0:0.1:3*pi;
z1=sin(x);
z2=sin(2.*x);
z3=sin(3.*x);
y1=zeros(size(x));
y3=ones(size(x));
y2=y3./2;
plot3(x,y1,z1,'r',x,y2,z2,'b',x,y3,z3,'g');
grid on;
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
``` ```t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
grid on;
axis square;
``` ```turns = 40*pi;
t = linspace(0,turns,4000);
x = cos(t).*(turns-t)./turns;
y = sin(t).*(turns-t)./turns;
z = t./turns;
plot3(x,y,z);
grid on;
``` ## 3. Surface drawing

• [X,Y]=meshgrid(x,y): returns 2D grid coordinates based on the coordinates contained in vectors X and y. That is to say, X and Y given above are just a vector, while drawing a net graph requires all points on the surface surrounded by X and y, and meshgrid(x,y) gives all points on this surface.
```x = -2:1:2;
y = -2:1:2;
[X,Y] = meshgrid(x,y)
``` • surf (x, y, Z) creates a three-dimensional surface that is a three-dimensional surface with a pure edge color and a solid face. This function plots the values in the matrix as the height above the mesh in the x-y plane defined by and. The color of the surface varies according to the specified height. (draw mesh and fill with color)
• The difference between mesh and surf: surf will paste the color on it;
```x = -3.5:0.2:3.5;
y = -3.5:0.2:3.5;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
subplot(1,2,1);
mesh(X,Y,Z);
subplot(1,2,2);
surf(X,Y,Z);
``` • Now the new version of Matlab usually uses surf (x, y, X. * exp (- X. ^ 2 - (y ') directly^ 2) ) can also get the above effect. as follows
```x = -3.5:0.2:3.5;
y = -3.5:0.2:3.5;
subplot(1,2,1);
mesh(x,y,x.*exp(-x.^2-(y').^2));
subplot(1,2,2);
surf(x,y,x.*exp(-x.^2-(y').^2));
``` ## 4. Matrix contour map

```x = -3.5:0.2:3.5;
y = -3.5:0.2:3.5;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
subplot(2,1,1);
mesh(X,Y,Z);
axis square;
subplot(2,1,2);
contour(X,Y,Z);
axis square;
``` • Adding a value after contour can make contour draw lines more closely; For example, contour(Z,[-.45:.05:.45]);

• We can also mark the value on the graph and use the clabel instruction: clabel(C,h);

• You can also color contour. Contour (), f means fill;

```x = -3.5:0.2:3.5;
y = -3.5:0.2:3.5;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
subplot(1,3,1);
contour(Z,[-.45:.05:.45]);
axis square;
subplot(1,3,2);
[C,h] = contour(Z);
clabel(C,h);
axis square;
subplot(1,3,3);
contourf(Z);
axis square;
``` practice ```x=-2:0.1:2;
y=-2:0.1:2;
[X,Y]=meshgrid(x,y);%Draw mesh
Z=X.*exp(-X.^2-Y.^2);
[C,h]=contourf(Z,[-0.4:0.05:0.4]);%Fill, change the tightness of the line, and prepare to add digital representation
axis square;%Display axis
``` ## 5. Contour map under grid surface map and surface map

```x = -3.5:0.2:3.5;
y = -3.5:0.2:3.5;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
subplot(1,2,1);
meshc(X,Y,Z);
subplot(1,2,2);
surfc(X,Y,Z);
``` ## 6. Viewpoint control and lighting setting

• View (Az,El), where Az is the azimuth angle and El is the altitude angle; You can also enter three parameters, view(x,y,z), where (x,y,z) is a vector in the rectangular coordinate system.
```sphere(50);
light('Position',[1 3 2]);%Add lights to make the ball more three-dimensional
light('Position',[-3 -1 3]);
material shiny;
axis vis3d off;%Do not display 3D coordinate system
set(gcf,'Color',[1 1 1]);
view(-45,20);%This can determine the angle
``` • You can rotate to view the sphere: use the 3D rotation option of the graphical interface. At this time, the spherical coordinate angle representation of observation will appear in the lower left corner • Define the lighting position and color of light:
```[X, Y, Z] = sphere(64);
h = surf(X, Y, Z);
axis square vis3d off;
reds = zeros(256, 3);
reds(:, 1) = (0:256.-1)/255;
colormap(reds);
lighting phong;
set(h, 'AmbientStrength', 0.75, 'DiffuseStrength', 0.5);
L1 = light('Position', [-1, -1, -1]);
``` ```set(L1, 'Position', [-1, -1, 1]);
``` ```set(L1, 'Color', 'g');
``` ## 7. Draw polygon

• patch() Draw one or more filled polygon areas
```v = [0 0 0; 1 0 0 ; 1 1 0; 0 1 0; 0.25 0.25 1; 0.75 0.25 1; 0.75 0.75 1; 0.25 0.75 1];
f = [1 2 3 4; 5 6 7 8; 1 2 6 5; 2 3 7 6; 3 4 8 7; 4 1 5 8];
subplot(1,2,1);
patch('Vertices', v, 'Faces', f, 'FaceVertexCData',hsv(6),'FaceColor','flat');
view(3);
axis square tight;
grid on;
subplot(1,2,2);
patch('Vertices', v, 'Faces', f, 'FaceVertexCData',hsv(8),'FaceColor','interp');
view(3);
axis square tight;
grid on;
``` practice

```load cape
X=conv2(ones(9,9)/81,cumsum(cumsum(randn(100,100)),2));
surf(X,'EdgeColor','none','EdgeLighting','Phong','FaceColor','interp');
colormap(map);
caxis([-10,300]);
grid off; axis off;
``` # summary

The above is the content of section 6. This part introduces the high-order drawing part of matlab.

Tags: MATLAB

Posted by erme on Fri, 15 Apr 2022 20:12:14 +0930