MATLAB 程式設計/繪圖
plot 命令繪製 Y 中資料的二維線圖與 X 中對應值的對比。
對於第一個 MATLAB 圖表,我們將繪製經典的線性方程 y = mx +c
在 MATLAB 中,要進行繪圖,我們需要遵循以下具體工作流程
(a) 指定要使用的 x 值的範圍 (b) 指定帶有 x 變數的 y 方程 (c) 繪製圖形

對於示例,我們需要繪製方程 ,其中 x 的範圍為 0 到 30
在 MATLAB 中,我們輸入以下內容
x = 0:30; %declare x = 0 to 30
y=(5*x) +8 ; % declare equation
plot(x,y) %plot the line chart
我們可以得到如下所示的簡單折線圖
正如你在左邊看到的,我們可以得到線性線的圖表圖。
恭喜,你已經繪製了 MATLAB 中的第一個圖表。
這是如何在 MATLAB 中繪製圖表的 基本思路。
在下一節中,我們將使用相同的圖表來美化圖表,使其更具個性化/獨特
以下是一些增強圖表的方法(使圖表更易於理解/更具吸引力,方便讀者理解)
請注意,所有圖表增強功能都需要在 plot 命令之後/下方定義,並且一些屬性需要在繪圖函式中定義。
以下是一些可以用來增強圖表圖的屬性,分別是
(a) 座標軸標籤
(b) 網格
(c) 圖例
(d) 標記
(d) 標題

我們可以使用 xlabel 和 ylabel 來標記座標軸,示例如下。
對於自定義,我們使用以下約定
xlabel 或 ylabel(要顯示的文字,屬性名稱 1,屬性值名稱 1,...,屬性名稱 n,屬性值名稱 n)
如下所示,我們可以使用多個屬性來自定義座標軸標籤。
xlabel('Population of dogs','Color','b','FontWeight','bold','FontAngle','italic')
% x label to display "Population of dogs" with blue colour fonts, bold and italic
ylabel({'Weeks','for year 2022'},'FontSize',15,'FontName','Times New Roman')
% y label to display 2 lines of "Weeks for year of 2022" with font size 15 and using font 'Times New Roman'

如上所示的原始圖表,很難看出某些線圖是與右側座標軸相關的。
我們可以使用網格來追蹤某個 x 值與哪個 y 值相關。
我們可以使用 grid 函式,並使用以下 MATLAB 命令
grid on
%turn on grid
grid minor
% turn on the minor gridlines / subset of the major gridlines
還有一個屬性是網格次要,它將繪製更小的網格刻度,即 grid minor
要使用網格次要,你需要先透過鍵入 grid on 來開啟網格。

我們可以使用以下命令在圖表圖中新增圖例:legend
例如,以下示例需要將繪圖線標記如下
legend('y=(5*x) +8','Location','northeast')
我們可以看到圖例顯示在 東北 位置,這是圖形的預設位置
我們可以透過在位置中新增關鍵字 outside 來定義圖例在圖表區域內或圖表區域外的具體位置

你可以在 plot 命令內的圖表圖中新增標記。
plot(x,y,marker_commands)
例如,假設我們想要使用菱形標記,因此我們輸入以下命令
plot(x,y,'-d') %the line - indicate the line to connect the diamond shapes
我們將得到一個帶有菱形標記的圖表。
以下標記命令可以用於繪圖,如下所示
| 標記命令 | 標記形狀 |
|---|---|
| 'o' | 圓圈符號 |
| '+' | 加號 |
| '*' | 星號 |
| '.' | 點 |
| 'd' | 菱形 |
| 'h' | 六角星(六芒星) |
| 's' | 正方形 |
| 'p' | 五角星(五芒星) |
| 'x' | 十字 |
| '^' | 向上箭頭三角形 |
| 'v' | 向下箭頭三角形 |
| '<' | 向左箭頭三角形 |
| '>' | 向右箭頭三角形 |

我們可以透過新增 title 命令來新增圖表圖的標題
與上面的座標軸標籤相同,title 命令遵循相同的約定
title(要顯示的文字,屬性名稱 1,屬性值名稱 1,...,屬性名稱 n,屬性值名稱 n)
如下所示,我們可以自定義標題
title({'Populations of dogs in 2022 ','by weeks'}, 'Color','g','FontSize',14,'FontName','Lucida Console')
%display the title in two lines with green text , font size of 14 and with font Lucida COnsole
在本例中,我們將繪製一個簡單的圓圈。
angles = linspace(0, 2*pi);
radius = 20; % radius of circle is 20
CenterX = 50; %coordinate of circle center point at x axis is 50
CenterY = 50; %coordinate of circle center point at y axis is 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;
在本例中,以下程式碼將建立一個圖形,用於比較兩種演算法在處理器數量增加時的 加速比。
生成的圖形如下所示。

>> 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 next graph on same figure
>> plot(x,z);
>> hold off;
>> xlabel('Number of processors');
>> ylabel('Speedup');
>> saveas(h,'graph.eps',eps);