Matlab (advanced drawing)

       

Table of contents

outline

 1.Special Plots

1.1 loglog (double logarithmic scale chart)

1.3 plotyy (create a graph with two y-axes)

 1.4yyaxis (create a graph with two y-axes)

1.5 bar

3D bar chart (bar3)

1.6 pie(pie chart)

3D pie chart

1.7 polar

 2.Stairs And Ste ladder diagram

 3.Boxplot box plot and Error Bar error bar chart

3.1 boxplot

 3.2 errorbar

 4.fill (create a two-dimensional fill patch)

 5.RGB color

 6.imagesc (display images using scaled colors)

7. Color Bars and Schemes

 8.3D Plots

 8.1.plot3

 8.2 mesh() and surf()

 8.3 contour()

 8.4 meshc() and surfc()

 9.view() perspective

10.Light light():

 11.patch()


       In the process of our actual application of Matlab, we often need more difficult drawing techniques to meet our needs. Superb techniques often require the simplest techniques. Let us find out today! ! !

outline

 1.Special Plots

plots function
loglog Graph with logarithmic scale for both axes
semilogx The x-axis is a logarithmic scale and the y-axis is a linear scale graph.
semilogy The y-axis is a logarithmic scale and the x-axis is a linear scale.
yyaxis A graph with y mark labels on the left and right
hist Histogram, column chart
bar Bar chart
pie pie chart
polar plumb Polar plot

1.1 loglog (double logarithmic scale chart)

Syntax 1:loglog(x,y)  Apply a base 10 logarithmic scale on the x and y axes to plot the x and y coordinates

  • To plot a set of coordinates connected by line segments, specify x and y as vectors of the same length
  • Plot multiple sets of coordinates on the same set of axes, specifying at least one of x and y as a matrix

Example:

will  x be defined as a vector consisting of 50 logarithmically spaced numbers in the interval [10−1,102]. will be  y defined as 2x. Then draw the sum  x and  ycall  grid the function to display the grid lines

x = logspace(-1,2);%loglog默认就是以10为底的指数,所以这里只用定义上标数值便可
y = 2.^x;
loglog(x,y)
grid on

 Syntax 2:loglog(x1,y1,...,xn,yn)  Plot multiple pairs of x and y coordinates on the same set of coordinate axes. This syntax is an alternative to specifying coordinates as a matrix.

Example:

Creates a  vector consisting of x-  coordinates and two   vectors consisting of y- coordinates.  Draw two lines by passing them comma-separated  x - y  pairs  .loglog

x = logspace(-1,2);
y1 = 10.^x;
y2 = 1./10.^x;
loglog(x,y1,x,y2)
grid on

 Syntax 3:loglog(x,y,LineSpec)  Create a drawing using specified line styles, markers, and colors

Example:

Create a set of  x-  and  y-  coordinates and display them in a log-log plot. Specify the line style to  's' display square markers without connecting lines. Specify the marker fill color as an RGB triplet  [0 0.447 0.741], which corresponds to dark blue.

x = logspace(-1,2,20);
y = 10.^x;
loglog(x,y,'s','MarkerFaceColor',[0 0.447 0.741])
grid on

1.2 semilogx (double logarithmic plot, x-axis logarithmic scale)

Syntax 1:semilogx(x,y)  Plot the x and y coordinates using a base 10 logarithmic scale on the x-axis and a linear scale on the y-axis.

  • To plot a set of coordinates connected by line segments, specify  X and  Y as vectors of the same length.

  • To plot multiple sets of coordinates on the same set of axes, specify   at least one of X or  as a matrix.Y

Example:

will  be defined as a  vector consisting of logarithmically spaced values  x ​​from  0.1 to  , will be  defined as   a copy of . Create   a   linear-log plot of sum and call   the function to display the grid lines.100yxxygrid

x = logspace(-1,2);
y = x;
semilogx(x,y)
grid on

 Syntax 2:semilogx(x1,y1,...,xn,yn)  Plot multiple pairs of x and y coordinates on the same set of coordinate axes. This syntax is an alternative to specifying coordinates as a matrix

Example:

Creates a vector consisting of logarithmically spaced  x-  coordinates and two   vectors consisting of y- coordinates.  Draw two lines by passing them comma-separated  x - y  pairs  .semilogx

%y = logspace(a,b) 生成一个由在 10^a 和 10^b(10 的 N 次幂)之间的 50 个对数间距点组成的行向量 y。logspace 函数对于创建频率向量特别有用。该函数是 linspace 和“:”运算符的对数等价函数。
x = logspace(-1,2);
y1 = x;
y2 = -x;
semilogx(x,y1,x,y2)
grid on

 Syntax 3:semilogx(x,y,LineSpec)  Create a drawing using specified line styles, markers, and colors.

Example:

Create a set of  x-  and  y-  coordinates and display them in a linear-log plot. Specify the line style to  'o' display circular markers without connecting lines. Specify the marker fill color as an RGB triplet  [0 0.447 0.741], which corresponds to dark blue.

%在10的幂10^-1和10^2之间生成15个点
x = logspace(-1,2,15);
y = 12 + x;
semilogx(x,y,'o','MarkerFaceColor',[0 0.447 0.741])
grid on

1.3 plotyy (create a graph with two y-axes)

Not recommended, there are version compatibility issues

Syntax 1: plotyy(X1,Y1,X2,Y2) plots  a Y1 pair  X1 of graphs, displaying  the y-  axis label on the left, and simultaneously draws  Y2 a pair  of graphs, displaying the y-  axis label X2 on the right  .

Example:

  • Plot two data sets on one graph using two different y-axes
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
figure 
plotyy(x,y1,x,y2)

  • Plot two data sets on one graph using two y-axes, add titles and axis labels
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);

figure % new figure
%hAx是两个坐标轴的句柄,hLine1和hLine2分别是第一条曲线和第二条曲线的句柄
[hAx,hLine1,hLine2] = plotyy(x,y1,x,y2);


title('Multiple Decay Rates')
xlabel('Time (\musec)')

ylabel(hAx(1),'Slow Decay') % left y-axis 
ylabel(hAx(2),'Fast Decay') % right y-axis

 1.4yyaxis (create a graph with two y-axes)

Syntax 1:yyaxis left  Activate the side of the current axes associated with the left  y-  axis. Subsequent graphics commands target the left side. If there are not two y- axes in the current axes   , this command will add a second  y-  axis. If there are no axes, this command creates the axes first.

Example:

Create   an axes with y- axes on the left and right sides.  Plots a set of data based on the left  y- axis. Then use  yyaxis right activate the right side to cause subsequent graphics functions to act on that side.  Plot the second set of data  based on the right  y- axis and set the range for the right y-  axis.

x = linspace(0,10);
y = sin(3*x);
yyaxis left
plot(x,y)

z = sin(3*x).*exp(0.5*x);
yyaxis right
plot(x,z)
ylim([-150 150])

Syntax 2:yyaxis right  Activate the side of the current axes associated with the right  y-  axis. Subsequent graphics commands target the right side.

Syntax 3:yyaxis(ax,___)  Specify ax the active side of the axes (not the current axes). If there are not two y- axes in the axes  , this command will add a second  y-  axis. Specify the axes as the first input argument. Use single quotes to  enclose'left' the and 'right'

Starting in R2019b, we can   display tiled plots using the tiledlayout and  functions. nexttileCall  tiledlayout the function to create a 2×1 tile layout. Call  nexttile the function to create the axes object  ax1 and  ax2.  Add a second  y- axis in the top axes by specifying  ax1 as  the first input  . If you do not specify an axes,  a second  y-  axis will be added to the current axes.yyaxisyyaxis

>> colororder({'b','m'})%可以更改左右侧的颜色 b-蓝色  m-粉色

x = linspace(1,10);
tiledlayout(2,1)%创建一个2*1分块图布局

% Top plot
ax1 = nexttile;%调用函数nexttilt函数创建坐标区对象
yyaxis(ax1,'left')
plot(ax1,x,sin(x))
yyaxis(ax1,'right')
plot(ax1,x,exp(x))

% Bottom plot
ax2 = nexttile;
plot(ax2,1:10)

1.5 bar

Syntax 1:bar(y)  Create a bar chart y in which each element corresponds to a bar.

  • To plot a single bar series, specify  y as a vector of length m. The bars  1 are placed sequentially from to m along the x-axis.

  • To plot multiple bar series,  y specify as a matrix, one column for each series.

Example:

  • Create a bar chart
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y)

  • Specify the bar position along the x-axis
x = 1900:10:2000;
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(x,y)

  •  Specify bar width
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,0.4)%将各条形的宽度设置为各条形可用总空间的 40%。

  •  Show bar group
y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];%显示四个条形组,每一组包含三个条形。
bar(y)

  •  Show stacked bar chart
y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
bar(y,'stacked')%为矩阵中的每一行显示一个条形。每个条形的高度是行中各元素之和。

  •  Specify labels at the ends of bars
x = [1 2 3];
vals = [2 3 6; 11 23 26];
b = bar(x,vals);

       We can display the value at the end of the bar sequence by obtaining the XEndPoints and YEndPoints properties of the Bar object, obtain the coordinates of the end of the bar, pass these coordinates to the text function, and specify the vertical and horizontal alignment so that the value is displayed at Centered above the end of the bar

xtips1 = b(1).XEndPoints;
ytips1 = b(1).YEndPoints;
labels1 = string(b(1).YData);
text(xtips1,ytips1,labels1,'HorizontalAlignment','center',...
    'VerticalAlignment','bottom')

xtips2 = b(2).XEndPoints;
ytips2 = b(2).YEndPoints;
labels2 = string(b(2).YData);
text(xtips2,ytips2,labels2,'HorizontalAlignment','center',...
    'VerticalAlignment','bottom')

  • 3D bar chart (bar3)

x = [1 2 5 4 8]; y = [x;1:5];
subplot(1,3,1); bar(x); title('A bargraph of vector x');
subplot(1,3,2); bar(y); title('A bargraph of vector y');
subplot(1,3,3); bar3(y); title('A 3D bargraph');

1.6 pie(pie chart)

Syntax 1:pie(x)  Draw a pie chart using  X the data in question. Each slice of a pie chart represents  X an element in the pie chart.

  • If  sum(X) ≤ 1, X the value in directly specifies the area of ​​the pie chart sector. If  sum(X) < 1, pie only part of the pie chart is drawn.

  • If  sum(X) > 1, then  pie the  X/sum(X) values ​​are normalized to determine the area of ​​each slice of the pie chart.

  • If  X of  categorical data type, the sectors correspond to the categories. The area of ​​each sector is the number of elements in the category divided by  X the number of elements in .

Example:

  • Create a pie chart with offset sectors
X = [1 3 0.5 2.5 2];
pie(X)%创建向量 X 的饼图。

We can offset the second and fourth pie slices by setting the corresponding explode element to 1

explode = [0 1 0 1 0];
pie(X,explode)

  • Specify text labels for pie charts
X = 1:3;
labels = {'斗破','火影','海贼'};
pie(X,labels)

  •  Modify the text label of a pie chart
>> X = 1:3;
labels = {'斗破','火影','海贼'};
p=pie(X,labels)

 Gets the text object of the label "Profit". Change its color and font size. Set properties using dot notation.

t=p(6);
>> t.BackgroundColor='yellow';
>> t.EdgeColor='red';
>> t.FontSize=15

t = 

  Text (海贼) - 属性:

                 String: '海贼'
               FontSize: 15
             FontWeight: 'normal'
               FontName: 'Helvetica'
                  Color: [0 0 0]
    HorizontalAlignment: 'left'
               Position: [1.1000 -2.6942e-16 0]
                  Units: 'data'

  显示 所有属性 可修改属性

        BackgroundColor: [1 1 0]
           BeingDeleted: 'off'
             BusyAction: 'queue'
          ButtonDownFcn: ''
               Children: [0×0 GraphicsPlaceholder]
               Clipping: 'off'
                  Color: [0 0 0]
              CreateFcn: ''
              DeleteFcn: ''
              EdgeColor: [1 0 0]
                Editing: 'off'
                 Extent: [1.1000 -0.0897 0.2804 0.1794]
              FontAngle: 'normal'
               FontName: 'Helvetica'
               FontSize: 15
          FontSmoothing: 'on'
              FontUnits: 'points'
             FontWeight: 'normal'
       HandleVisibility: 'on'
                HitTest: 'on'
    HorizontalAlignment: 'left'
            Interpreter: 'tex'
          Interruptible: 'on'
              LineStyle: '-'
              LineWidth: 0.5000
                 Margin: 3
                 Parent: [1×1 Axes]
          PickableParts: 'visible'
               Position: [1.1000 -2.6942e-16 0]
               Rotation: 0
               Selected: 'off'
     SelectionHighlight: 'on'
                 String: '海贼'
                    Tag: ''
                   Type: 'text'
          UIContextMenu: [0×0 GraphicsPlaceholder]
                  Units: 'data'
               UserData: []
      VerticalAlignment: 'middle'
                Visible: 'on'
  •  Specify the format of percent labels
X = [1/3 2/3];
pie(X,'%.3f%%')%要在标签中包含百分号,请在表达式末尾指定 '%%'。

 

  • 3D pie chart

>> X = 1:3;
labels = {'斗破','火影','海贼'};
pie3(X,labels)

1.7 polar

%theta 弧度角  r 每个点的半径值
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);

 2.Stairs And Ste ladder diagram

stair ladder diagram
stem Plot discrete sequence data
x = linspace(0, 4*pi, 40); y = sin(x);
subplot(1,2,1); stairs(y);
subplot(1,2,2); stem(y);

 3.Boxplot box plot and Error Bar error bar chart

boxplot Visualizing summary statistics with boxplots
errorbar Line graph with error bars

3.1 boxplot

Boxplots provide visualization of summary statistics for sample data and include the following features:

  • The bottom and top of each box represent the 25th and 75th percentiles of the sample, respectively. The distance between the bottom and top of each bin represents the interquartile range.

  • The red line in the middle of each box represents the sample median. If the median is not at the center of the bin, the plot shows sample skewness.

  • Whiskers are lines that extend upward from the top and downward from the bottom of each box. The whiskers extend from the endpoint of the interquartile range to the farthest observation ( neighbor ) within the length of the whisker.

  • Observations that exceed the whisker length are marked as outliers. By default, outliers are values ​​that are more than 1.5 times the interquartile range from the bottom or top of the bin. However, you can adjust this value by using additional input parameters. Outliers appear as red + signs.

  • Notches show the variability of the median across samples. The width of the gap is calculated so that boxes with non-overlapping gaps have different medians at the 5% significance level. The significance levels are based on the assumption of normal distribution, but median comparisons can reasonably be considered robust for other distributions. Comparing boxplot medians is like a visual hypothesis test, similar to  a t  -test for means. In some cases, the notch may extend to the outside of the box.

 3.2 errorbar

errorbar(x,y,neg,pos) Draw a vertical error bar at each data point, where  neg determine the length below the data point and pos determine the length above the data point.

 4.fill (create a two-dimensional fill patch)

Syntax 1:fill(x,y,c)  Draw a filled polygon area as a patch, with its vertices at the (x,y) positions specified by x and y.

  • To draw an area, specify  X and  Y as vectors.

  • To draw multiple regions, specify  X and  Y as a matrix, where each column corresponds to a polygon.

Example:

x = [0 4 5 2 1];
y = [0 0 2 4 3];
fill(x,y,'r')

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');

 practise:

 5.RGB color

 Color self-check sheet:

 6.imagesc (display images using scaled colors)

Syntax 1:imagesc(C) Display the data in  the array  C as an image using all the colors in the color map. C Each element specifies the color of a pixel of the image. The resulting image is a  m× n pixel grid, where  m and  n are  C the number of rows and columns, respectively. The row and column indices of these elements determine the center of the corresponding pixel.

Example:

Create matrix C. Image showing the data in C. Adds a colorbar to the plot to display the current colormap. By default, imagesc the scale color range is so that the image uses all colors in the color map, with  C the smallest value mapping to the first color in the color map and the largest value mapping to the last color.

>> C = [0 2 4 6; 8 10 12 14; 16 18 20 22];
imagesc(C)
>> colorbar

  •  向三维视图的坐标区添加图像
Z = 10 + peaks;
surf(Z)
hold on
imagesc(Z)

 Syntax 2:imagesc(x,y,C)  Specify the image location. Use  x and  y to specify   the position of the corner corresponding to C(1,1) and  . C(m,n)To specify both corners, set  x and  y to two-element vectors. To specify the first corner and let  imagesc determine the other, set  x and  y as scalar values. The image will be stretched and oriented as needed.

Example:

Position the image so that it is   between 5 and 8 on the  x- axis and  between 3 and 6 on the y- axis.

x = [5 8];
y = [3 6];
C = [0 2 4 6; 8 10 12 14; 16 18 20 22];
imagesc(x,y,C)

Note: The corresponding  C(1,1) pixel is centered on point (5,3). The corresponding  C(3,4) pixel is displayed centered on point (8,6). imagesc Determine the position and orientation of the rest of the image between these two points.

7. Color Bars and Schemes

>> [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); axis square; xlabel('x'); ylabel('y');
>> colorbar
>> colormap(hot);

 colormap(cool);

colormap(spring);

 Color list:

 8.3D Plots

plot3 3D line image
surf 3D shaded surface plot
surfc Contour plot of 3D shaded surface
surface Create surface objects
meshc Draw contour plots under grid plots
contour Matrix contour plot
contourf Filled 2D contour plot

How to view a 2D plane with a 3D perspective:

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

method one:

 Method Two:

>> x=0:0.1:2*pi;
plot(x,sin(x));
>> rotate3d on

 8.1.plot3

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');

 Principle of three-dimensional surface graph:

  • Typically used in plotting functions: Z=f(x,y)
  • Need to provide Matlab with a set of (x, y, z) points
x = -2:1:2;
y = -2:1:2;
[X,Y] = meshgrid(x,y)

 8.2 mesh() and surf()

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);

 8.3 contour()

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;

 Representation of various contour lines:

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;

 8.4 meshc() and surfc()

%比mesh()和surf()多了等高线
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);

 9. view () perspective

>> sphere(50); shading flat;
light('Position',[1 3 2]);
light('Position',[-3 -1 3]);
material shiny;
axis vis3d off;
set(gcf,'Color',[1 1 1]);
view(-45,20);

10.Light 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); shading interp; 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');

 11.patch()

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;

       Matlab is indeed very powerful in drawing. Some of the pictures in our game can also be drawn using Matlab. Come on, boy! ! !

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

Guess you like

Origin blog.csdn.net/dfdbb6b/article/details/132601572