Main Content

创建二维线图

创建一个简单的线图并标记坐标区。通过更改线条颜色、线型和添加标记来自定义线图的外观。

创建线图

使用 plot 函数创建二维线图。例如,绘制从 0 到 2π 之间的正弦函数值。

x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y)

标记坐标区并添加标题。

xlabel('x')
ylabel('sin(x)')
title('Plot of the Sine Function')

Figure contains an axes object. The axes object with title Plot of the Sine Function, xlabel x, ylabel sin(x) contains an object of type line.

绘制多个线条

默认情况下,MATLAB 会在执行每个绘图命令之前清空图窗。使用 figure 命令打开一个新的图窗窗口。可以使用 hold on 命令绘制多个线条。在使用 hold off 或关闭窗口之前,当前图窗窗口中会显示所有绘图。

figure
x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y)

hold on 
y2 = cos(x);
plot(x,y2)
hold off

Figure contains an axes object. The axes object contains 2 objects of type line.

更改线条外观

通过在调用 plot 函数时包含可选的线条设定,可以更改线条颜色、线型或添加标记。例如:

  • ':' 绘制点线。

  • 'g:' 绘制绿色点线。

  • 'g:*' 绘制带有星号标记的绿色点线。

  • '*' 绘制不带线条的星号标记。

符号可以按任意顺序显示。不需要同时指定所有三个特征(线条颜色、线型和标记)。有关不同样式选项的详细信息,请参阅 plot 函数页。

例如,绘制一条点线。添加第二个图,该图使用带有圆形标记的红色虚线。

x = linspace(0,2*pi,50);
y = sin(x);
plot(x,y,':')

hold on 
y2 = cos(x);
plot(x,y2,'--ro')
hold off

Figure contains an axes object. The axes object contains 2 objects of type line.

通过忽略线条设定中的线型选项,仅绘制数据点。

x = linspace(0,2*pi,25);
y = sin(x);
plot(x,y,'o')

Figure contains an axes object. The axes contains a line object which displays its values using only markers.

更改线条对象的属性

通过更改用来创建绘图的 Line 对象的属性,还可以自定义绘图的外观。

创建一个线图。将创建的 Line 对象赋给变量 ln。显示画面上显示常用属性,例如 ColorLineStyleLineWidth

x = linspace(0,2*pi,25);
y = sin(x);
ln = plot(x,y)
ln = 
  Line with properties:

              Color: [0 0.4470 0.7410]
          LineStyle: '-'
          LineWidth: 0.5000
             Marker: 'none'
         MarkerSize: 6
    MarkerFaceColor: 'none'
              XData: [0 0.2618 0.5236 0.7854 1.0472 1.3090 1.5708 1.8326 2.0944 2.3562 2.6180 2.8798 3.1416 3.4034 3.6652 3.9270 4.1888 4.4506 4.7124 4.9742 5.2360 5.4978 5.7596 6.0214 6.2832]
              YData: [0 0.2588 0.5000 0.7071 0.8660 0.9659 1 0.9659 0.8660 0.7071 0.5000 0.2588 1.2246e-16 -0.2588 -0.5000 -0.7071 -0.8660 -0.9659 -1 -0.9659 -0.8660 -0.7071 -0.5000 -0.2588 -2.4493e-16]

  Use GET to show all properties

要访问各个属性,请使用圆点表示法。例如,将线宽更改为 2 磅并将线条颜色设置为 RGB 三元组颜色值,在本例中为 [0 0.5 0.5]。添加蓝色圆形标记。

ln.LineWidth = 2;
ln.Color = [0 0.5 0.5];
ln.Marker = 'o';
ln.MarkerEdgeColor = 'b';

Figure contains an axes object. The axes object contains an object of type line.

另请参阅

| | |

相关主题