BudiBadu Logo
Samplebadu

MATLAB by Example: Plots

R2023b

Data visualization is a core strength of MATLAB. This sample demonstrates 2D plotting with labels and legends.

Code

% Generate data
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);

% Create plot
figure;
plot(x, y1, '-b', 'LineWidth', 2); % Blue solid line
hold on; % Retain current plot
plot(x, y2, '--r', 'LineWidth', 2); % Red dashed line

% Add annotations
title('Sine and Cosine Waves');
xlabel('Time (s)');
ylabel('Amplitude');
legend('Sin', 'Cos');
grid on;

hold off;

Explanation

MATLAB excels at data visualization. The plot function is the most common tool for creating 2D line plots. It takes x and y vectors as arguments. You can customize the appearance of the line using a format string (e.g., '-b' for a solid blue line, '--r' for a dashed red line) and property-value pairs (e.g., 'LineWidth', 2).

By default, calling plot overwrites the existing figure. To display multiple lines on the same set of axes, you use the hold on command. This "freezes" the current plot so that subsequent plot commands add to it rather than replacing it. hold off releases this state.

A good plot needs context. Functions like title, xlabel, ylabel, and legend allow you to add necessary annotations. The grid on command adds a grid to the background, making it easier to read values off the graph. MATLAB also supports 3D plotting, histograms, scatter plots, and more.

Code Breakdown

8
plot(x, y1, ...) creates the visualization. The third argument specifies style and color.
9
hold on prevents the first plot from being erased when the second plot command runs.