2-D Plotting

Line specifications combine a color (r g b c m y k w), a line style (- -- : -.) and a marker (o + * .

Concept

Line specifications combine a color (r g b c m y k w), a line style (- -- : -.) and a marker (o + * . x s d ^).

Points (size/color per point) histogram (MATLAB), hist stairs, stem semilogx, semilogy, loglog Logarithmic axes (Bode plots, spectra) Measurements with uncertainty yyaxis (MATLAB) Figures, Axes and Handles

figure creates a window, subplot(m, n, k) (or tiledlayout/nexttile in MATLAB) arranges several axes, gca/gcf return the current axes/figure. Every graphics object is a handle whose properties can be read or set (set(h, 'LineWidth', 2), dot notation ax.FontSize = 12 in MATLAB).

Export: print(fig, 'file.png', '-dpng'), saveas, exportgraphics (MATLAB R2020a+).

plot(x, y, 'r--o', 'LineWidth', 1.5)   % color, line style, marker
xlabel('Time (s)'), ylabel('Voltage (V)'), title('...')
legend('measured', 'nominal'), grid on, axis([0 1 11 13])
hold on / hold off                      % add more lines to the same axes

Why It Matters

A good plot is often the fastest way to find a problem in measurement data and the clearest way to present results.

Syntax

figure; plot(t, v); hold on; plot(t, vref, '--'); hold off;
subplot(2, 1, 1); bar(values); subplot(2, 1, 2); histogram(data, 20);
print(gcf, 'result.png', '-dpng', '-r150');

Example

18.1 A labelled line plot, subplots, bar chart and histogram

The script creates figures off-screen ('Visible', 'off') so it can run unattended, saves one as PNG and prints facts about the figures instead of showing them.

% Plots are drawn off-screen here and saved to PNG; the script reports what it created.
t = 0:0.01:1;
v = 12 + 0.5 * sin(2 * pi * 5 * t);
fig = figure('Visible', 'off');
plot(t, v, 'b-', 'LineWidth', 1.5)
hold on
plot(t, 12 * ones(size(t)), 'r--')
hold off
xlabel('Time (s)'), ylabel('Voltage (V)')
title('Battery voltage ripple')
legend('measured', 'nominal')
grid on
ax = gca;
fprintf('lines in the axes: %d, x-limits [%g %g], title "%s"\n', numel(get(ax, 'Children')), xlim, get(get(ax, 'Title'), 'String'))
print(fig, 'ripple.png', '-dpng');
info = dir('ripple.png');
fprintf('saved ripple.png: %d bytes > 0: %d\n', info.bytes, info.bytes > 0)

fig2 = figure('Visible', 'off');
subplot(2, 1, 1), bar([12.6 11.9 12.9]), title('Voltage per ECU')
set(gca, 'XTickLabel', {'VCU', 'BMS', 'GW'})
subplot(2, 1, 2), histogram_data = randn(1, 1000); hist(histogram_data, 20), title('Noise histogram')
fprintf('figure 2 has %d axes\n', numel(findobj(fig2, 'Type', 'axes')))
close all
delete('ripple.png');

Expected Result

The axes contain the two plotted lines, the title set with title is readable back from the axes, the PNG file was written, and the second figure has two axes created by subplot.

lines in the axes: 2, x-limits [0 1], title "Battery voltage ripple"
saved ripple.png: 22057 bytes > 0: 1
figure 2 has 2 axes

Common Mistakes

Forgetting hold on (each plot replaces the previous one).

Axis labels without units.

plot(y) when plot(x, y) was intended (x becomes the sample index).

Too many lines in one axes; use subplots.

Best Practices

Always label axes with units, add a legend for multiple lines, and use grid on.

Script your plots so they can be regenerated from data.

Export with a fixed resolution for reports.

Interview Relevance

Low–medium: "how do you plot two lines in one figure?", "what does hold on do?", "how do you create subplots?", "how do you save a figure?".

Practice Questions

Plot sin and cos on 0–2π with a legend and different line styles.

Plot a Bode magnitude plot with semilogx.

Create a 2×2 subplot figure of four different plot types.

Save a figure at 300 dpi as PNG.

Quick Quiz

Q1. (Multiple choice) Which keeps previous lines when plotting new ones? A) grid on B) hold on C) figure D) axis on Answer: B.

Q2. (Predict the output) How many lines did the first figure's axes contain?

Answer: 2 (verified).

Q3. (True/False) 'r--o' means a red dashed line with circle markers.

Answer: True. Q4. (Find the bug) A script plots measured data, then plot(t, limit) — only the limit line is visible.

Answer: Missing hold on between the two plot calls.

Coding Challenge

Create (off-screen) a figure with the step response 1 - exp(-t/0.5) for t = 0:0.01:3, mark the time constant point with a red circle, label everything, and print the y-value at t = 0.5.

t = 0:0.01:3;
y = 1 - exp(-t / 0.5);
fig = figure('Visible', 'off');
plot(t, y, 'b-'), hold on
plot(0.5, 1 - exp(-1), 'ro'), hold off
xlabel('Time (s)'), ylabel('Response'), title('First-order step response'), grid on
fprintf('y at t = tau: %.4f\n', interp1(t, y, 0.5))
close(fig)