绘图简介(plot 命令)

plot 命令用于绘制二维线图,将 Y 中的数据与对应的 X 值进行绘图。


绘制线性图线

我们以最经典的线性方程 y = mx + c 为例来进行 MATLAB 的第一次绘图。

绘图流程如下:

  1. 指定 x 的取值范围

  2. 根据 x 写出 y 的表达式

  3. 使用 plot 函数绘图


没有增强的MATLAB绘图
MATLAB 简单绘图

例如,我们绘制方程 y = 5x + 8,其中 x 范围是从 0 到 30。

在 MATLAB 中输入:

x = 0:30;       % 定义 x 从 0 到 30
y = (5 * x) + 8; % 定义 y 方程
plot(x, y)      % 绘图

这样我们就得到了一个简单的线性图。

🎉 恭喜你完成了 MATLAB 中的第一个图像绘制!


美化图表(Enhance the chart plots)

为了让图更美观、更具有表达力,我们可以使用一些增强技巧,主要包括以下内容:

  • 坐标轴标签(Axis Label)

  • 网格(Grid)

  • 图例(Legend)

  • 标记(Marker)

  • 标题(Title)

注意:这些增强命令必须写在 plot 命令之后


坐标轴标签(Axes labels)

使用 xlabelylabel 来添加轴标签。例如:

xlabel('Population of dogs', 'Color', 'b', 'FontWeight', 'bold', 'FontAngle', 'italic')
ylabel({'Weeks', 'for year 2022'}, 'FontSize', 15, 'FontName', 'Times New Roman')




我们可以看到网格线和小网格线
网格(Grid)

开启主网格和次网格:

grid on      % 开启主网格
grid minor   % 开启次网格(必须在开启主网格后使用)




图例(Legend)

我们可以在图形的东北面看到图表的图例
为图表添加图例:

legend('y = (5*x) + 8', 'Location', 'northeast')

你可以通过 'Location' 属性指定图例的位置,还可以使用 'outside' 将图例放置在图框之外。





标记(Marker)

我们可以看到菱形的标记
你可以在绘图时添加标记(marker)样式:

plot(x, y, '-d') % 用菱形标记连成线

常用的标记命令如下:

命令 形状
'o' 圆圈
'+' 加号
'*' 星号
'.'
'd' 菱形
'h' 六角星
's' 方形
'p' 五角星
'x' 叉号
'^' 上三角
'v' 下三角
'<' 左三角
'>' 右三角

标题(Title)

我们可以看到图表顶部的绿色标题
使用 title 添加标题:

title({'Populations of dogs in 2022', 'by weeks'}, 'Color', 'g', 'FontSize', 14, 'FontName', 'Lucida Console')

此处我们设置了绿色字体、字号 14、字体为 Lucida Console,并显示成两行标题。


其他示例

示例 1:绘制一个圆

angles = linspace(0, 2*pi);
radius = 20;
CenterX = 50;
CenterY = 50;
x = radius * cos(angles) + CenterX;
y = radius * sin(angles) + CenterY;
plot(x, y, 'b-', 'LineWidth', 2);
title("Circle")
hold on;
plot(CenterX, CenterY, 'k+', 'LineWidth', 3, 'MarkerSize', 14);
grid on;
axis equal;

示例 2:比较两个算法在多处理器下的加速比

x = [1 2 4 8];
y = [1 2 1.95 3.79];
z = [1 1.73 2.02 3.84]; 
h = plot(x, y, '--');
hold on;
plot(x, z);
hold off;
xlabel('Number of processors');
ylabel('Speedup');
saveas(h, 'graph.eps', 'eps');

外部链接


这就是 MATLAB 中绘制图表以及图形美化的完整基础流程与技巧。是否想我帮你整理一份通用绘图模板代码?


Last modified: Wednesday, 16 April 2025, 10:05 AM