Lecture 13 Practice Session

EE1021 Programming for Engineers - Lecture 13

Basri ERDOGAN

Visualisation and Plotting

Getting Started

  • Before we start plotting, we need some data.
  • Load the PlottingData.mat file:
    • From the command line
    • Through the toolbar
    • Or by dragging it into your workspace

1. Basic plotting

Simple Line Plot

  • Create a very basic line plot.
  • Type the following command into the command window and press return:
plot(PlotEEG)
  • This opens a new graphics window entitled ‘Figure 1’.
  • Identify the thin blue line (EEG trace).
  • Note that the x-axis is simply numbered from 1 to 1537 (size of variable).

Plotting vs Time

  • The previous plot lacked a defined x-axis.
  • The data is a 3s EEG trace recorded at 512Hz.
  • Use the accompanying time stamp variable to see ‘real time’:
plot(PlotEEGTime, PlotEEG)
  • Uses plot(x,y) syntax.
  • Units of x-axis now correspond to time in seconds.

Plotting Matrices

  • PlotEEG was a single vector (one line).
  • If we plot a matrix, MATLAB plots each column as a separate line:
plot(PlotMEGTime, PlotMEG)

Transposing Data

  • If data is arranged in rows, use the apostrophe shortcut (') to transpose.
  • Compare the previous output with this:
plot(PlotMEG')
  • Now plots each of the 361 rows as separate lines.
  • Result: A very colourful mess!

Error Bars

  • Useful for displaying experimental results.
  • Adds error bars of user-defined length to each point.
errorbar(ErrorbarX, ErrorbarY, ErrorbarSE)
  • Length of error bar is defined by the third input ErrorbarSE.

Scatter Plots

  • Created with scatter function.
  • Must provide both x and y axis data points.
scatter(ScatterX, ScatterY)

2. Figure Handling

Managing Figure Windows

  • plot commands overwrite the previously displayed figure by default.
  • To open a new specific Figure window:
figure
  • To close the current figure panel:
close
  • Note: This only closes the most recent figure panel (currently in use).

Closing Specific Figures

  • If you open a new figure, but then click on an old ‘Figure 1’ window…
  • …and type close:
figure
% (Make 'Figure 1' active by clicking it)
close
  • MATLAB closes the active window (‘Figure 1’), not the new one.

Closing All Figures

  • If you have several figure windows open:
figure
figure
figure
  • Close all of them at once with:
close all

Holding Figures

  • To plot multiple datasets on the same graph without overwriting:
  • Use hold on.
plot(PlotEEGTime, PlotEEG)   % Plot first line
hold on                      % 'Hold' the figure
plot(PlotEEGTime, PlotEEG2)  % Plot second line
hold off                     % Stop 'holding'
  • Next plot command will overwrite the figure:
plot(PlotEEGTime, PlotEEG3)

3. Axis limits

Setting Limits

  • MATLAB automatically assigns axis limits to fit data.
  • To define limits manually: xlim([min max]) and ylim([min max]).
ylim([-2000 2000])
xlim([PlotEEGTime(1) PlotEEGTime(end)])
  • Can use numbers or variables for min/max.

Other Axis Commands

  • axis tight: Sets limits to exactly match data range.
  • axis square: Makes plot window square.
  • axis off: Removes axes, labels, and background.
axis tight
axis square
axis off

4. Figure text

Adding Labels

  • Label axes using xlabel and ylabel.
close all
scatter(ScatterX, ScatterY)
xlabel('Independent Variable')
ylabel('Dependent Variable')
  • Display text over multiple lines using a cell array:
xlabel({'Independent';'Variable'})

Titles and Text

  • Add a title:
title('Lots of nice blue circles')
  • Add text at specific (x,y) coordinates:
text(0.8, 0, 'Text at [0.8,0]!')
text(0, 0.8, 'Text at [0,0.8]!')
text(0, 0, 'Text at the origin!')

Text Formatting Properties

  • ‘FontSize’: size in points.
  • ‘FontName’: font family.
  • ‘FontWeight’: ‘bold’ or ‘normal’.
  • ‘FontAngle’: ‘italic’ or ‘normal’.
title('Title', 'FontSize', 24)
title('Title', 'FontSize', 24, 'FontName', 'Courier')
title('Title', 'FontSize', 24, 'FontWeight', 'bold')
title('Title', 'FontSize', 24, 'FontAngle', 'italic')
  • Use listfonts to see available fonts.

5. Editing figure properties

GUI Editing

  • Method 1: Edit -> Figure Properties… in Figure window toolbar.
  • Opens a panel to browse and change properties.
  • Lines: Change weight, colour, style, markers.
  • Axes: Click background to edit labels, title, font, ticks.

Command Line Editing I

  • Method 2: Pass additional inputs to plot commands.
  • LineWidth, Color, LineStyle.
plot(PlotEEGTime, PlotEEG, 'LineWidth', 3, 'Color', 'r', 'LineStyle', '--')
  • Order of properties doesn’t matter.
plot(PlotEEGTime, PlotEEG, 'Color', 'r', 'LineStyle', '--', 'LineWidth', 3)

Combined Plotting

  • Use hold on to mix styles:
hold on
plot(PlotEEGTime, PlotEEG2, 'Color', 'g', 'LineStyle', ':', 'LineWidth', 2)
hold off

RGB Colors

  • Specify custom colors using [R G B] (0-1 values).
plot(PlotEEGTime, PlotEEG, 'Color', [0.1 0.5 0.8], 'LineWidth', 3)

Shortcut Syntax

  • Specify color, line style, and marker in one string.
  • e.g., 'r--*' (red, dashed, star marker).
plot(PlotEEGTime, PlotEEG, 'r--*')
hold on
plot(PlotEEGTime, PlotEEG2, 'b:o')
hold off

ErrorBar Styles

  • Use properties to customize error bars (e.g., no line).
errorbar(ErrorbarX, ErrorbarY, ErrorbarSE, ...
    'LineStyle', 'none', ...
    'Marker', 'o', ...
    'MarkerSize', 10, ...
    'MarkerFaceColor', 'k', ...
    'MarkerEdgeColor', 'k', ...
    'Color', 'k')

The set and get functions

  • set(handle, property, value)
  • get(handle, property)
  • gca: Shortcut for “Get Current Axis”.
get(gca)  % List all properties of current axis

Setting Axis Properties

  • Change tick direction:
set(gca, 'TickDir', 'out')
  • Remove tick labels:
set(gca, 'XTickLabel', [])
  • Custom tick labels:
set(gca, 'YTickLabel', {'one','two','three','four','five','six','seven'})
  • Remove box outline:
box off

6. Subplots

Creating Subplots

  • subplot(rows, cols, index)
  • Creates a grid of plots in one window.
subplot(2, 2, 1)
plot(PlotEEGTime, PlotEEG)

subplot(2, 2, 2)
plot(PlotEEGTime, PlotEEG2)

subplot(2, 2, 3)
plot(PlotEEGTime, PlotEEG3)

subplot(2, 2, 4)
plot(PlotMEGTime, PlotMEG)

Subplot Handles

  • Assign output of subplot to variables (h1, h2…).
  • Control specific panels later using these handles.
close
h1 = subplot(2, 2, 1);
h2 = subplot(2, 2, 2);
h3 = subplot(2, 2, 3);
h4 = subplot(2, 2, 4);

plot(h1, PlotEEGTime, PlotEEG)
% ... plotting on other handles ...

set(h1, 'XLim', [min(PlotEEGTime) max(PlotEEGTime)])
xlabel(h1, 'Time (s)')

Spanning Subplots

  • Pass a vector of indices to span multiple positions.
h1 = subplot(2, 3, 1:2);    % Spans first two columns of top row
h2 = subplot(2, 3, [3 6]);  % Spans right column (top and bottom)
h3 = subplot(2, 3, 4);      % Just one spot

plot(h1, PlotEEGTime, PlotEEG)
plot(h2, PlotEEGTime, PlotEEG2)
plot(h3, PlotEEGTime, PlotEEG3)

7. Bar charts and histograms

Bar Charts

  • bar(Y) or bar(X, Y).
close
bar(BarY)
bar(BarX, BarY)
  • Define width (3rd input):
bar(BarX, BarY, 0.4)
  • Define properties:
bar(BarX, BarY, 0.4, 'FaceColor', 'w', 'EdgeColor', 'k', 'LineWidth', 3)

Histograms

  • hist(data): Default 10 bins.
Gaussian = randn(10000, 1);
hist(Gaussian)
  • Specify number of bins:
hist(Gaussian, 101)
  • Specify bin centers:
hist(Gaussian, -5:0.1:5)

8. 2D plots

Contour Plots

  • contourf(Z) or contourf(X, Y, Z).
contourf(Morlet)
contourf(MorletTime, MorletFreq, Morlet)
  • Specify number of levels (4th input):
contourf(Morlet, 50)
  • Remove contour lines:
contourf(MorletTime, MorletFreq, Morlet, 50, 'LineStyle', 'none')

Formatting Contour Plots

xlabel('Time since stimulus onset (s)', 'FontSize', 14)
ylabel('Frequency (Hz)', 'FontSize', 14)
title('Spectrogram of Hippocampal LFP', 'FontSize', 20)
set(gca, 'YScale', 'log')

Imagesc

  • Similar to contour plots but as an image.
  • Note: imagesc reverses the Y-axis by default (image coordinates).
figure
imagesc(MorletTime, MorletFreq, Morlet)
xlabel('Time', 'FontSize', 14)
ylabel('Freq', 'FontSize', 14)
  • Correct Y-axis direction:
set(gca, 'YScale', 'log', 'YDir', 'normal')