Skip to content

MATLAB - Plotting

MATLAB is renowned for its powerful and flexible 2D and 3D plotting capabilities. Creating publication-quality visualizations is a core strength of the language. This guide covers the modern, object-oriented approach to creating and customizing plots.

The fundamental workflow for creating a plot involves these steps:

  • 1. Prepare Data: Create the vectors or matrices that hold your data. The linspace function is excellent for generating evenly spaced data for function plotting.
  • 2. Create a Figure: Use the figure command to open a new window for your plot.
  • 3. Plot the Data: Use a plotting function like plot, scatter, or bar to create the initial graph. It’s a best practice to get a handle to the plot object for later customization.
  • 4. Customize and Annotate: Add titles, axis labels, legends, and adjust colors, line styles, and other properties to make the plot clear and informative.

Let’s plot the function y = sin(x) from 0 to 2π. Note the use of linspace to create a smooth curve.

% 1. Prepare Data
x = linspace(0, 2*pi, 200); % Create 200 points from 0 to 2*pi
y = sin(x);
% 2. Create a Figure
figure;
% 3. Plot the Data
plot(x, y, 'LineWidth', 2); % Plot with a line width of 2
% 4. Customize and Annotate
title('Plot of the Sine Function');
xlabel('Angle (radians)');
ylabel('sin(x)');
grid on; % Add a grid
axis([0, 2*pi, -1.2, 1.2]); % Set axis limits [xmin, xmax, ymin, ymax]

Plotting Multiple Functions on the Same Graph

Section titled “Plotting Multiple Functions on the Same Graph”

The modern and most flexible way to plot multiple lines on the same axes is to use the hold on and hold off commands. This approach is more readable and extensible than older syntax.

x = linspace(0, 10, 150);
y1 = sin(x);
y2 = cos(x);
figure;
plot(x, y1, 'b-', 'LineWidth', 2); % Plot sin(x) as a solid blue line
hold on; % Keep the current plot active for adding more lines
plot(x, y2, 'r--', 'LineWidth', 2); % Plot cos(x) as a dashed red line
title('Sine and Cosine Functions');
xlabel('x');
ylabel('Function Value');
legend('sin(x)', 'cos(x)', 'Location', 'southwest'); % Add a legend
hold off; % Release the plot (new plots will replace it)
grid on;

MATLAB provides extensive options for customizing the appearance of your plots. You can specify color, line style, and marker symbols as a single string argument or as separate name-value pairs.

SpecifierTypeValues
r, g, b, k, m, c, y, wColorRed, Green, Blue, Black, Magenta, Cyan, Yellow, White
-Line StyleSolid line (default)
--Line StyleDashed line
:Line StyleDotted line
-.Line StyleDash-dot line
o, +, *, ., x, s, dMarkerCircle, Plus, Asterisk, Point, Cross, Square, Diamond

Example: plot(x, y, '--mo') creates a dashed magenta line with circle markers at each data point.

The subplot function allows you to display multiple plots in a grid within a single figure window. The syntax is subplot(m, n, p), where m is the number of rows, n is the number of columns, and p is the index of the current plot (counted row-wise).

x = linspace(0, 5, 100);
figure;
% First subplot (top)
subplot(2, 1, 1);
y1 = exp(-1.5*x) .* sin(10*x);
plot(x, y1);
title('Subplot 1: Damped Sine Wave');
ylabel('Amplitude');
grid on;
% Second subplot (bottom)
subplot(2, 1, 2);
y2 = exp(-0.5*x) .* sin(10*x);
plot(x, y2);
title('Subplot 2: Less Damped Sine Wave');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

MATLAB’s visualization library extends far beyond line plots. Here are a few other essential plot types:

  • scatter: Creates a scatter plot, ideal for visualizing the relationship between two variables.
  • bar: Creates a bar chart, useful for comparing values across different categories.
  • histogram: Creates a histogram, which shows the distribution of a set of data.
  • errorbar: Creates a line plot with error bars at each data point.

For full control over your plot’s appearance, you can get handles to graphics objects and modify their properties directly using dot notation. To save your final plot, the exportgraphics function is recommended for high-quality output.

% ... (previous plotting code) ...
% Get handle to current axes and change font size
ax = gca;
ax.FontSize = 14;
% Save the current figure to a PNG file
exportgraphics(ax, 'my_beautiful_plot.png', 'Resolution', 300);