Basic functions and auxiliary operations of two-dimensional graphics drawing in MATLAB

  • A two-dimensional graph is a plane graph that connects data points on plane coordinates. Different coordinate systems can be used. In addition to the rectangular coordinate system, logarithmic coordinates and polar coordinates can also be used. Data points can be given in vector or matrix form, and the type can be real or complex. The drawing of two-dimensional curved shapes is undoubtedly the basis of other drawing operations.

1. Basic functions for drawing two-dimensional curves

  • In MATLAB, the basic drawing function is plotthe function , which can be used to draw different two-dimensional curves.

1. Basic usage of the plot function

  • plotfunction for plotting xy xyThe linear coordinate curve on the xy plane, so a set of xx is requiredThe x coordinate and the yycorresponding to each pointy coordinates, so that you can plotthe xxxyyy is a two-dimensional curve with horizontal and vertical coordinates.
  • plotThe basic calling format of the function is as follows:
    plot(x,y)
  • Among them, xxxyyy is a vector of the same length, used to store xxrespectivelyx coordinate andyyy- coordinate data.
  • For example, at 0 ≤ x ≤ 2 π 0\le x\le2\pi0xIn the 2 π interval, we draw the curvey = 2 e − 0.5 x sin ⁡ ( 2 π x ) y=2e^{-0.5x}\sin(2\pi x)y=2e _- 0.5 xsin ( 2 π x ) _
  • The procedure is as follows:
x=0:pi/100:2*pi;
y=2*exp(-0.5*x).*sin(2*pi*x);
plot(x,y)
  • After the program runs, open an image window in which to draw the function curve.

insert image description here

  • What needs to be noted here is that seeking yyWhen y is used, the dot multiplication operation is used between the exponential function and the sine function. Since 2 is a scalar, the multiplication operation can be used between 2 and the exponential function. Thus, the vectorxxx and vectoryyy contains the same number of elements,y ( i ) y(i)y ( i ) isx ( i ) x(i)x ( i ) point er function value.
  • For example, we plot the curve: { x = t cos ⁡ 3 ty = t sin ⁡ 2 t − π ≤ t ≤ π \left\{\begin{matrix}x=t\cos 3t \\y=t\sin^{ 2} t \end{matrix}\right. \begin{matrix} -\pi \le t\le \pi \end{matrix}{ x=tcos3 ty=tsin2tptp
  • This is a two-dimensional curve given in the form of a parametric equation. As long as the parameter vector is given, then x, yx, and y are calculated separatelyThe x and y vectors can draw the function curve. The procedure is as follows:
t=-pi:pi/100:pi;
x=t.*cos(3*t);
y=t.*sin(t).*sin(t);
plot(x,y)
  • After the program runs, the obtained two-dimensional curve is as follows.

insert image description here

  • The arguments x , yx , yplot of the function above improveIt is very common for x and y to be vectors of the same length. However, there will be some changes in the actual application, which will be explained separately below.
  • (1) When xxx is the vector,yyWhen y is a matrix, xxThe length of x and the matrixyyy must have an equal number of rows or columns.
  • if xxThe length of x is equal to yyThe number of rows of y , then use xxxyyEach column of y draws a curve for the horizontal and vertical coordinates, and the number of curves is equal toyyThe number of columns of y .
  • if xxThe length of x is equal to yyThe number of columns of y , then use xxxyyEach row of y draws a curve on the horizontal and vertical coordinates, and the number of curves is equal toyyThe number of rows of y .
  • if yyy is a square matrix,xxlength of x and matrix yyIf the number of rows or columns of y is equal, use xxxyyEach column of y draws a curve for the horizontal and vertical coordinates. For example, the following program plots both sine and cosine curves in the same coordinates.
x=linspace(0,2*pi,100);
y=[sin(x),cos(x)];
plot(x,y)
  • The program first generates a row vector xxx , and then calculate the row vector sin(xxx ) and cos(xxx ), and form them into matrixyyThe two rows of y . Finally, two curves are drawn simultaneously in the same coordinates.
  • when xxx is the matrix,yyThe length of y must be equal to the matrixxxThe number of rows or columns of x , plotted similarly to the previous case.
  • (2) 当x、yx、yWhen x and y are matrices of the same type, usex, yx, yThe corresponding column elements of x and y are horizontal and vertical coordinates to draw curves respectively, and the number of curves is equal to the number of columns of the matrix. For example, to draw sine and cosine curves simultaneously in the same coordinate, the following program can be used.
t=linspace(0,2*pi,100) ; 
x=[t;t]';
y=[sin(t);cos(t)]';
plot(x,y) 
  • (3) plotThe simplest calling format of the function is to contain only one input parameter, namely plot(x). In this case, when xxWhen x is a real vector, draw a curve with the subscript of the vector element as the abscissa and the element value as the ordinate, which is actually a line graph.
  • when xxWhen x is a complex vector, draw a curve with the real part and imaginary part of the vector element as the abscissa and ordinate, respectively. For example, the program below draws a unit circle.
t=0:0.01:2*pi;
x=exp(i*t);  %x是一个复数向量
plot (x)
  • It should be noted here that i in the program is an imaginary unit, so xxx is a complex vector. To ensure this, i cannot be assigned another value.
  • when xxWhen x is a real matrix, draw the curve of the element value of each column relative to its subscript by column, and the number of curves is equal toxxThe number of columns of the x- matrix. When the input parameter is a complex matrix, multiple curves are drawn by column with the real part and imaginary part of the element as the horizontal and vertical coordinates. For example, the program below draws 3 concentric circles.
t=0:0.01:2*pi;
x=exp(i*t);
y=[x;2*x;3*x]';
plot(y)

2. The plot function with multiple input parameters

  • plotThe function can contain several sets of vector pairs, and each vector pair can draw a curve. The corresponding calling format is as follows:
plot(x1,y1,x2,y2,...,xn,yn)
  • (1) When the input parameters are all vectors, x 1 x1x1 andy1, x2 y1, x2y 1 , x 2 andy 2 , … , xn y2, …, xny 2 x nis iny n form a set of vector pairs respectively, and the length of each set of vector pairs can be different. Each vector pair can draw a curve, so that multiple curves can be drawn in the same coordinates. For example, the following program can simultaneously draw 3 sinusoids in the same coordinates.
x=linspace(0,2*pi,100);
plot(x,sin(x),x,2*sin(x),x,3*sin(x))
  • (2) When the input parameter has a matrix form, the paired x, yx, yx and y draw curves according to the horizontal and vertical coordinates of the corresponding column elements, and
    the number of curve lines is equal to the number of columns in the matrix. Analyze the curves drawn by the following programs.
x=linspace(0,2*pi,100);
y1=sin(x);
y2=2*sin(x);
y3=3*sin(x);
x=[x;x;x]';
y=[y1;y2;y3]';
plot(x,y,x,cos(x))
  • x x xyyy is a matrix with 3 columns, they form input parameter pairs, and draw 3 sinusoidal curves,xxx and cos(xxx ) are vectors that form pairs of input arguments to draw a cosine curve.

3. The plot function with options

  • MATLAB provides several plotting options that determine the line style, color, and data point labeling of plotted curves. These options can be used in combination. For example, b- . represents a blue dotted line, and y:d represents a yellow dashed line with a diamond marking the data points.
  • When the option is omitted, MATLAB stipulates that the line type should always be a solid line, and the color specified by the ColorOrder attribute of the current coordinate axis will be used automatically (there are 7 colors by default), and there will be no data point marker.
  • The linetype options are shown in the table below.
options line type options line type
- implementation (default) -. dotted line
: dotted line double line
  • Color options are shown in the table below.
serial number options color serial number options color
1 b(blue) blue 5 m(magenta) Magenta
2 g(green) green 6 y(yellow) yellow
3 r(red) red 7 k(black) black
4 c(cyan) blue 8 w(white) White
  • The marker symbol options are shown in the table below.
options mark symbol options mark symbol
. point v (letter) down triangle symbol
o (letter) the circle ^ up triangle symbol
x (letter) Cross < left facing triangle symbol
+ plus > right facing triangle symbol
* Asterisk p(pentagram) pentagram
s(square) Square character h(hexagram) Hexagram
d(diamond) Rhombus
  • To set the curve style, you can add drawing options to plotthe function , and the calling format is as follows:
plot(x1,y1,选项1,x2,y2,选项2,...,xn,yn,选项n)
  • For example, plotting the curve y = 2 e − 0.5 x sin ⁡ ( 2 π x ) y=2e^{-0.5x}\sin(2\pi x) in the same coordinates with different lines and colorsy=2e _- 0.5 xsin ( 2 π x ) and its envelope.
  • The procedure is as follows:
x=(0:pi/100:2*pi)';
y1=2*exp(-0.5*x)*[1,-1];
y2=2*exp(-0.5*x).*sin(2*pi*x);
x1=(0:12)/2;
y3=2*exp(-0.5*x1).*sin(2*pi*x1);
plot(x,y1,'k:',x,y2,'b--',x1,y3,'rp');
  • The program running results are shown below. plotThe function contains 3 sets of drawing parameters, the first set draws two envelopes with black dotted lines, and the second set draws the curve yy with blue double-drawn linesy , the third group marks the data points discretely with red five-pointed stars. The first command in the program converts a row vector to a column vector using the matrix transpose operator.

insert image description here

4. Double ordinate function plotyy

  • In MATLAB, if you need to draw two graphs with different ordinate scales, you can use the plotyy function, and
    its calling format is as follows:
plotyy(x1,y1,x2,y2)
  • where, x 1 , y 1 x1, y1x 1 , y 1 corresponds to a curve,x 2 , y 2 x2, y2x 2 , y 2 corresponds to another curve. The abscissa has the same scale, the ordinate has two, and the left ordinate is used forx 1 , y 1 x1, y1x 1 , y 1 data pair, the right ordinate is used for x2, y2$ data pair.
  • The double ordinate graph can draw two functions with different dimensions and different orders of magnitude in the same coordinate, which is beneficial to the comparative analysis of graph data.
  • For example, plotting the curve y = 2 e − 0.5 x sin ⁡ ( 2 π x ) y=2e^{-0.5x}\sin(2\pi x) in the same coordinates with different scalesy=2e _- 0.5 xsin ( 2 π x ) and curvey = sinxy=sinxy=s in x _
  • The procedure is as follows:
x=0:pi/100:2*pi;
y1=exp(-0.5*x).*sin(2*pi*x);
y2=sin(x);
plotyy(x,y1,x,y2);
  • The result of running the program is shown below.

insert image description here

2. Auxiliary operations for drawing and drawing images

  • After the graphics are drawn, some auxiliary operations may be required on the graphics to make the meaning of the graphics clearer and more readable.

1. Graphic annotation

  • While drawing a graph, you can add some descriptions to the graph, such as the name of the graph, the description of the coordinate axes, and the meaning of a certain part of the graph, etc. These operations are called adding graph annotations. The calling format of the graphics annotation function is as follows:
    title (图形名称)
    xlabel (x轴说明)
    ylabel (y轴说明)
    text (x,y,图形说明)
    legend (图例1,图例2,)
  • titleThe and xlabeland ylabelfunctions are used to describe the names of the graphics and axes respectively.
  • textThe function is to add a graphical description at (x, y) coordinates.
  • gtextIt can be used to add text description. When this command is executed, the cross cursor will automatically move with the mouse, and the text can be placed at the cross cursor by clicking the mouse. For example, use gtext('cos(x)) to place the string cos(x).
  • legendThe function is used to mark the legend with the line type, color or data point used to draw the curve. The legend is placed in the blank space of the graph. The user can also move the legend with the mouse to place it at the desired position.
  • Except for legendthe function , other functions are also applicable to 3D graphs. It should be noted that the z coordinate axis description uses zlabelthe function.
  • In addition to standard ASCII characters, the explanatory text in the above functions can also use control characters in LaTeX (LaTeX is a very popular mathematical typesetting software) format, so that Greek letters, mathematical symbols and formulas can be added to the graphics and so on.
  • Among the LaTeX characters supported by MATLAB, use \bf, \it, \rm control characters to define bold, italic and regular characters respectively, and the parts controlled by LaTeX characters should be enclosed in large brackets {}. For example, text(0.3,0.5,'The useful {\bf MATLAB}') will make the word MATLAB appear in boldface.
  • Some commonly used LaTeX characters are shown in the table below, and each character can be used alone or in combination with other characters and commands. For example, text(1,1,'sin({\omega}t+ {beta})) will get the annotation effect sin( ω \omegaω t+β \betab ).
identifier symbol identifier symbol identifier symbol
\alpha a \alphaa \upsilon υ \upsilonu \sim ∼ \sim
\beta β \betab \phi ϕ \phiϕ \leq ≤ \leq
\gamma γ \gamma c \chi χ \chih \infty ∞ \infty
\delta d \deltad \psi ψ \psip \clubsuit ♣ \clubsuit
\epsilon ϵ \epsilonϵ \omega ω \omegaoh \diamondsuit ♢ \diamondsuit
\zeta ζ \zetag \Gamma Γ \Gamma C \heartsuit ♡ \heartsuit
and the \etathe \Delta D \DeltaD \spadesuit ♠ \spadesuit
\theta θ \theta i \Theta Θ \Theta Th \leftrightarrow ↔ \leftrightarrow
\vartheta ϑ \vartheta ϑ \Lambda Λ \LambdaL \leftarrow ← \leftarrow
\iota i \iotai \Xi Ξ \Xi X \uparrow ↑ \uparrow
\kappa k \kappaK \Pi Π \PiPi \rightarrow → \rightarrow
\lambda λ \lambdal \Sigma Σ \Sigma S \downarrow ↓ \downarrow
\mu μ \mum \Upsilon Υ \UpsilonY \circ ∘ \circ
\not n \nun \Phi Φ \PhiPhi \pm ± \pm ±
\xi ξ \xi X \Psi Ψ \PsiPs \geq ≥ \geq
\pi π \piPi \Omega Ω \OmegaOh \properly
\rho ρ \rho r \for all ∀ \for all \partial ∂ \partial
\sigma σ \sigma p \exists ∃ \exists \bullet ∙ \bullet
\varsigma ς \varsigma s \in ∋ \in \div ÷ \div ÷
\ can τ \yeart \cong ≅ \cong \neq ≠ \neq=
\equiv ≡ \equiv \approx ≈ \approx \aleph ℵ \aleph A
\Im ℑ \Im \Re ℜ \Re \wp ℘ \wp
\otimes ⊗ \otimes \oplus \oplus \oslash ⊘ \oslash
\cap ∩ \cap \cup ∪ \cup \supseteq ⊇ \supseteq
\supset ⊃ \supset \subseteq ⊆ \subseteq \subset ⊂ \subset
\int ∫ \int \in ∈ \in \nabla ∇ \nabla
\rfloor ⌋ \rfloor \lceil ⌈ \lceil \ldots … \ldots
\lfloor ⌊ \lfloor \cdot ⋅ \cdot \prime ′ \prime
\perp ⊥ \perp \neg ¬ \neg ¬ \mid ∣ \mid
\wedge ∧ \wedge \times × \times × \copyright © \copyright c
\rceil ⌉ \rceil \surd √ \surd \varpi ϖ \varpi ϖ
\vee ∨ \vee \langle ⟨ \langle \rangle ⟩ \rangle
  • 除了上表中给出的字符定义以外,还可以通过标准的 LaTeX 命令来定义上标和下标,这样可以使得图形标注更加丰富多彩。如果想在某个字符后面添加上标,则可以在该字符后面跟一个由 A 字符引导的字符串。
  • 若想把多个字符作为指数,则应该使用大括号。例如,e^{axt} 对应的标注效果为 e a x t e^{axt} eaxt,而 e^axt 对应的标注效果为 e a x t e^{a}xt eaxt。类似地可以定义下标,下标是由下画线 _ 引导的。例如,X_{12} 对应的标注效果为 X 12 X_{12} X12

2. 坐标控制

  • 在绘制图形时,MATLAB 可以自动根据要绘制曲线数据的范围选择合适的坐标刻度,使得曲线能够尽可能清晰地显示出来。所以,在一般情况下用户不必选择坐标轴的刻度范围。但是,如果用户对坐标系不满意,可利用 axis 函数对其重新设定。该函数的调用格式如下:
axis( [xmin, xmax, ymin, ymax, zmin, zmax])
  • 如果只给出前 4 个参数,则 MATLAB 按照给出的 x 、 y x、y xy 轴的最小值和最大值选择坐标系范围,以便绘制出合适的二维曲线。
  • 如果给出了全部参数,则系统按照给出的 3 个坐标轴的最小值和最大值选择坐标系范围,以便绘制出合适的三维图形。
  • axis 函数功能丰富,常用的用法还有以下几种。
  • (1) axis equal 表示纵、横坐标轴采用等长刻度。
  • (2) axis square 表示产生正方形坐标系(默认为矩形)。
  • (3) axis auto 表示使用默认设置。
  • (4) axis off 表示取消坐标轴。
  • (5) axis on 表示显示坐标轴。
  • 给坐标加网格线可以用 grid 命令来控制。grid on/off 命令控制是画还是不画网格线,不带参数的 grid 命令在两种状态之间进行切换。
  • 给坐标加边框用 box 命令来控制。box on/off 命令控制是加还是不加边框线,不带参数的 box 命令在两种状态之间进行切换。
  • 例如,我们绘制分段函数曲线并添加图形标注。 f ( x ) = { x , 2 , 5 − x / 2 , 1 , 0 ≤ x < 4 4 ≤ x < 6 6 ≤ x < 8 x ≥ 8 f(x)=\left\{\begin{matrix}\sqrt{x} , \\2, \\5-x/2, \\1,\end{matrix}\right. \begin{matrix}0\le x< 4 \\4\le x< 6 \\6\le x< 8 \\x\ge 8 \end{matrix} f(x)= x ,2,5x/2,1,0x<44x<66x<8x8
  • 整体程序如下:
x=linspace(0,10,100);  %产生自变量向量x
y=[];  %y的初始值为空
for x0=x
    if x0>=8
        y=[y,1];  %将函数值追加到向量y
    elseif x0>=6
        y=[y,5-x0/2];
    elseif x0>=4
        y=[y,2];
    elseif x0>=0
        y=[y,sqrt(x0)];
    end
end
plot(x,y)
axis([0,10,0,2.5])  %设置坐标轴
title('分段函数曲线');  %加图形标题
xlabel('Variable X');  %加X轴说明
ylabel('Variable Y');  %加Y轴说明
text(2,1.3,'y=x^{1/2}');  %在指定位置添加图形说明
text(4.5,1.9,'y=2');
text(7.3,1.5,'y=5-x/2');
text(8.5,0.9,'y=1');
  • 程序运行结果如下。

insert image description here

3. 图形保持

  • 一般情况下,每执行一次绘图命令就刷新一次当前图形窗口,图形窗口原有图形将不复存在。
  • 若希望在已存在的图形上再继续添加新的图形,可使用图形保持命令 hold
  • hold on/off 命令控制是保持原有图形还是刷新原有图形,不带参数的 hold 命令在两种状态之间进行切换。
  • 例如,我们使用图形保持功能在同一坐标内绘制曲线 y = 2 e − 0.5 x sin ⁡ ( 2 π x ) y=2e^{-0.5x}\sin(2\pi x) y=2e0.5xsin ( 2 π x ) and its envelope.
  • The procedure is as follows:
x=(0:pi/100:2*pi)';
y1=2*exp(-0.5*x)*[1,-1];
y2=2*exp(-0.5*x).*sin (2*pi*x);
plot(x,y1,'b:');  %绘制两根包络线
axis([0,2*pi,-2,2]);  %设置坐标
hold on;  %设置图形保持状态
plot(x,y2,'k');  %绘制曲线
legend('包络线','包络线','曲线y');  %加图例
hold off;  %关闭图形保持
grid  %网格线控制
  • The result of the program running is as follows:

insert image description here

4. Splitting the graphics window

  • In practical applications, it is often necessary to draw several independent graphics in a graphics window, which requires the graphics to be divided. The divided graphics window consists of several drawing areas, and each drawing area can establish an independent coordinate system to draw graphics. Different graphs in the same graph window are called subplots.
  • The MATLAB system provides subplotthe function to divide the current graphics window into several drawing areas. Each area represents an independent subgraph, and is also an independent coordinate system. A certain area can be activated through subplotthe function . This area is the active area, and the drawing commands issued all act on the active area.
  • subplotThe function call format is as follows:
subplot (m,n,p)
  • This function divides the current graphics window into m × nm × nm×n drawing area, iemmm lines, each linennn drawing areas, the area numbers are numbered according to row priority, and theppthThe p areas are currently active areas. It is allowed to draw graphics independently in different coordinate systems in each drawing area.
  • For example, we draw sine, cosine, tangent, and cotangent curves simultaneously in the form of subgraphs in one graphics window.
  • The procedure is as follows:
x=linspace(0,2*pi,60);
y=sin(x);
z=cos(x);
t=sin(x)./(cos(x)+eps);
ct=cos(x)./(sin (x)+eps);

subplot(2,2,1);  %选择2x2个区中的1号区
plot(x,y);
title('sin(x)');
axis([0,2*pi,-1,1]);

subplot(2,2,2);  %选择2x2个区中的2号区
plot(x,z);
title('cos(x)');
axis([0,2*pi,-1,1]);

subplot(2,2,3);  %选择2x2个区中的3号区
plot(x,t);
title('tangent(x)');
axis([0,2*pi,-40,40]);

subplot(2,2,4);  %选择2x2个区中的4号区
plot(x,ct) ;
title('cotangent(x)');
axis([0,2*pi,-40,40]);
  • The program running result is shown in the figure below.

insert image description here

  • In the above example, the graph window is divided into 2×2 drawing areas, numbered from 1 to 4, and a graph is drawn in each area, which is the most regular situation. But in fact, more flexible segmentation is also possible, see the following procedure for details (It should be noted that the layout of the picture is based on the row, and secondly, you only need to count the specific position of each picture, large pictures and small pictures are not allowed overlap each other).
x=linspace(0,2*pi,60);
y=sin(x);
z=cos(x);
t=sin(x)./(cos(x)+eps);
ct=cos(x)./(sin (x)+eps);

subplot(2,2,1);  %选择2x2个区中的1号区
plot(x,y-1);
title('sin(x)-1');
axis([0,2*pi,-2,0]);

subplot(2,1,2);  %选择2x2个区中的2号区
plot(x,z-1);
title('cos(x)-1');
axis([0,2*pi,-2,0]);

subplot(4,4,3);  %选择4x4个区中的3号区
plot(x,y);
title('sin(x)');
axis([0,2*pi,-1,1]);

subplot(4,4,4);  %选择4x4个区中的4号区
plot(x,y);
title('cos(x)');
axis([0,2*pi,-1,1]);

subplot(4,4,7);  %选择4x4个区中的7号区
plot(x,t);
title('tangent(x)');
axis([0,2*pi,-40,40]);

subplot(4,4,8);  %选择4x4个区中的8号区
plot(x,ct) ;
title('cotangent(x)');
axis([0,2*pi,-40,40]);
  • The program running result is shown in the figure below.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_45891612/article/details/130739074