Visualisation, Plotting & Data Handling

EE1021 Programming for Engineers - Lecture 13

Basri Erdogan

Visualisation and Plotting

Basic Plotting I

  • You can create a basic line graph in MATLAB using the function plot.
  • plot(y) will plot your data (y) against an arbitrary (numbered) x-axis.
  • plot(x, y) will plot your data (y) against the corresponding x-axis locations in x.
  • If y is a matrix, the plot function will display all columns of y as separate lines.
  • For data arranged in rows, use the apostrophe shortcut ' to transpose the matrix.

Basic Plotting II

  • You can create a basic line graph with error bars using the function errorbar.
  • errorbar(x, y, SE) will plot data with error bars whose length is specified by SE.
  • Scatter plots can be created in MATLAB using the scatter function.
  • The scatter function requires a minimum of two inputs (i.e. both x and y data).

Plot Types Visual

Basic Figure Handling

  • The plot function automatically generates a new figure window, if one is not open.
  • The plot function automatically overwrites an existing figure window, if one is open.
  • To open an additional figure window, use the figure command.
  • To add lines to an existing figure, use the hold on / hold off commands.
  • You can close figures individually with the close command.
  • Note that this will close the most recently active figure.
  • You can close all figures with the close all command.

Axis Limits

  • MATLAB automatically scales figure axes to accommodate the data being plotted.
  • Axes limits can be manually controlled using xlim([min max]) and ylim([min max]).
  • The axis function can also be used adjust axes in several different ways.
  • axis tight fits the axes limits to the data exactly.
  • axis square makes the figure axes square, for display purposes.
  • axis off removes the axes, labels and background, for display purposes.
  • Each of these axis limit commands can be used on any MATLAB plot.

Axis Limits Visual

Figure Text

  • There are several functions for adding labels, titles and text to figures.
  • Axes can be labelled using the functions xlabel('string') and ylabel('string').
  • Titles can be added to a figure using the function title('string').
  • Text can be added to a figure using the function text(x_position, y_position, 'string').
  • Text added by these functions can also be formatted directly from the command line.
    • This is achieved by passing additional inputs to the function.
    • For example: title('string', 'FontSize', 24) or title('string', 'FontName', 'Times').

Figure Text Visual

xlabel('Time (s)', 'FontSize', 14)
ylabel('Amplitude (V)', 'FontSize', 14)

title('Damped Sine Wave Analysis', ...
      'FontSize', 24, ...
      'FontName', 'Serif')

text(2, 0.8, 'Peak Value', ...
     'FontSize', 16, ...
     'Color', 'red')

text(2, -0.5, 'y = sin(x) * e^{-0.1x}', ...
     'FontSize', 14, ...
     'FontAngle', 'italic', ...
     'BackgroundColor', 'white')

Editing Figure Properties I

  • There are two ways to edit the properties of a figure.
  • The first is through the figure window toolbar, by clicking Edit -> Figure Properties…
  • This brings up an additional panel at the bottom of the figure window.
  • Clicking on various parts of the figure then allows you to edit properties directly.
  • For example, click on or near the axes, and you can edit the labels, font and limits.
  • Clicking on the plotted line allows you to edit the colour, line style and marker style.

Figure Window Toolbar Visual

Editing Figure Properties II

  • The second way to edit a figure is directly from the command line.
  • Basic properties can be defined when first creating the plot.
  • These include LineWidth, LineStyle, and Color for lines…
  • …and Marker, MarkerEdgeColor, MarkerFaceColor and MarkerSize for markers.
  • For example: plot(x, y, 'LineWidth', 3, 'Color', 'r', 'LineStyle', '--')
  • The colour, line and marker style alone can be defined in a single set of apostrophes.
  • For example: plot(x, y, 'r--*')

MATLAB Color, LineStyle, and Marker Codes

Color

  • b: Blue (default)
  • g: Green
  • r: Red
  • k: Black
  • y: Yellow
  • w: White
  • c: Cyan
  • m: Magenta

LineStyle

  • -: Solid line (default)
  • --: Dashed line
  • -.: Dash-dot line
  • :: Dotted line
  • none: No line

Marker

  • o: Circle
  • .: Point
  • x: Cross
  • +: Plus sign
  • *: Asterisk
  • s: Square
  • d: Diamond
  • v/^: Triangles
  • p: Pentagram
  • h: Hexagram

Editing Figure Properties III

  • More complex properties can be adjusted using the set function.
  • The general syntax for this is set(FigureHandle, 'Property_Name', Value).
  • For example: set(gca, 'TickDir', 'out', 'Xscale', 'log').
  • There are a number of different properties that can be changed in this way.
  • These can be viewed by searching for ‘Axes Properties’ in MATLAB help.
  • The ‘figure handle’ identifies the figure that we wish to edit.
  • For now, we will use the shortcut gca, which specifies the ‘current’ figure.

Editing Figure Properties Visual

% Define line properties during plot creation
plot(x, y, ...
    'LineWidth', 2, ...
    'LineStyle', '--', ...
    'Color', 'b', ...
    'Marker', 'o', ...
    'MarkerSize', 8, ...
    'MarkerFaceColor', 'r', ...
    'MarkerEdgeColor', 'k');

% Edit axes properties using 'set'
set(gca, ...
    'TickDir', 'out', ...
    'FontSize', 14, ...
    'XGrid', 'on', ...
    'YGrid', 'on');

Subplots

  • Several different panels can be plotted within a single figure using subplot.
  • The syntax is: subplot(Panel_Rows, Panel_Columns, Panels_to_be_used).
  • Panels are numbered along each row.
  • For example, subplot(2,2,1) sets up a 2 x 2 square of panels, and plots in the first.
  • Plots can also be spread across multiple panels.

Advanced Figure Handling

  • When drawing subplots, figure handles can be used to control each panel separately.
  • This means assigning a variable to each panel.
  • This is achieved by providing the subplot function with an output variable.
  • For example, h1 = subplot(2,2,1).
  • Properties of that specific panel can then be controlled using set(h1, …) etc.

Subplot Example Visual

% Create a new figure
figure;

% First subplot: Sine wave
subplot(2, 2, 1);
plot(t, sin(t), 'b-');
title('Sine Wave');

% Second subplot: Scatter plot
subplot(2, 2, 2);
scatter(rand(1,20), rand(1,20), 'r');
title('Scatter Plot');

% Third subplot: Bar chart
subplot(2, 2, 3);
bar([10 25 15 30], 'g');
title('Bar Chart');

% Fourth subplot: Cosine wave
subplot(2, 2, 4);
plot(t, cos(t), 'k--');
title('Cosine Wave');

Bar Charts

  • Vertical and horizontal bar charts can be created using the bar and barh functions.
  • Like plot, bar(y) plots the data in y on an arbitrary x-axis of 1 to length(y)…
  • …while bar(x, y) plots the data in y at the x-axis positions defined in x.
  • The width of the bars can be defined by a third input, i.e. bar(x, y, width).
  • Other properties can be defined using the PropertyName, Value syntax from above.
  • For example: bar(x, y, 'FaceColor', 'r', 'EdgeColor', 'k').
  • A list of bar chart properties can be found by searching for ‘Barseries properties’.

Bar Charts Visual

x = [1, 2, 3, 4, 5];
y = [10, 25, 15, 30, 20];

% Create a bar chart with custom colors
bar(x, y, ...
    'FaceColor', 'r', ...
    'EdgeColor', 'k');

title('Bar Chart Example');
xlabel('Category');
ylabel('Values');

Histograms

  • Histograms can be created using the hist function.
  • Providing a single input will plot a histogram with 10 evenly spaced bins, i.e. hist(y).
  • The second input can be used to define the centre of the x-axis bins, i.e. hist(y,x).
  • …or to define the total number of evenly spaced bins, i.e. hist(y,n).
  • Note that the syntax differs from plot – input the data first, x-axis positions second.

Histograms Visual

% Generate random data
y = randn(1000, 1) * 10 + 50;

% Plot histogram with 20 bins
hist(y, 20);

% Customizing look (using bar properties for output of hist)
h = findobj(gca,'Type','patch');
set(h,'FaceColor','cyan','EdgeColor','k');

title('Histogram Example');
xlabel('Values');
ylabel('Frequency');

Contour Plots

  • Two dimensional plots can be created using contourf.
  • There are several ways to provide data to this function:
    • contourf(Z): Uses the column and row indices of Z as x and y coordinates.
    • contourf(X, Y, Z): Uses X and Y matrices to define the coordinates for Z.
  • Data Formats:
    • X and Y: Usually generated using meshgrid. X varies across columns, Y varies down rows.
    • Z: A matrix of the same size where Z(i,j) is the height/color at (X(i,j), Y(i,j)).
  • The contourf function also allows you to specify how many z gradations are plotted.
    • For example, contourf(x, y, c, n).

Contour Plots Visual

% Create coordinate grid
x = linspace(-3, 3, 100);
y = linspace(-3, 3, 100);
[X, Y] = meshgrid(x, y);

% Define function Z on grid
Z = 3*(1-X).^2.*exp(-(X.^2) - (Y+1).^2) ...
   - 10*(X/5 - X.^3 - Y.^5).*exp(-X.^2-Y.^2) ...
   - 1/3*exp(-(X+1).^2 - Y.^2);

% Plot filled contour with 20 levels
contourf(X, Y, Z, 20);
colorbar;
title('Filled Contour Plot');
xlabel('x'); ylabel('y');

Image Plots

  • Image plots can be created using imagesc.
  • Like contour plots, you can pass a single matrix or x/y coordinates:
    • imagesc(C) or imagesc(x, y, C).
  • Note: The imagesc function automatically inverts the y-axis (image coordinate system).
  • This can be corrected to standard Cartesian coordinates using:
    • set(gca, 'Ydir', 'normal') or axis xy.

Image Plots Visual

% Using the same Z data as before

% Plot as image
% imagesc scales colors to data range
imagesc(x, y, Z);
colorbar;

% Invert Y-axis to match 
% standard plot orientation
set(gca, 'Ydir', 'normal');

title('Image Plot (imagesc)');
xlabel('x'); ylabel('y');

Other Useful Plotting Functions

  • There are many different plotting functions within MATLAB.
  • Each of these can be controlled using the general syntax discussed above.
  • Information on the specific syntax used for each function can be found in the ‘Help’ file.
  • Some examples include:
    • plotyy: allows you to plot multiple lines on one figure with different y-axes.
    • pie: allows you to plot a pie chart (with one emerging segment!).
    • loglog, semilogx, semilogy: allows you plot one or more logarithmic axes.
    • surf: allows you to plot a 3D surface (like the MATLAB logo!).

Other Useful Plotting Tools

  • There are several buttons at the top of the Figure window that may be useful.
  • The ‘Data Cursor’ returns the x and y co-ordinates of any point clicked on.
  • The ‘Insert Legend’ button inserts an editable legend to annotate your figure.
  • The ‘Insert Colorbar’ button adds a ‘colorbar’ (i.e. z-axis scale) to your figure.
  • There are also buttons for zooming in and out of your figure.
  • Finally, it is important to note that you can save figures in several formats.
  • These include *.bmp, *.jpg, various Adobe Illustrator formats etc.
  • Figures saved in the native MATLAB *.fig format can be re-opened and edited.

Importing and Handling Data

Introduction: MATLAB vs Python

  • You are likely familiar with Python and NumPy.
  • MATLAB is very similar, but with some key differences:
    • Everything is a Matrix: Like numpy.array, but by default.
    • Indexing: MATLAB uses 1-based indexing A(1), while Python uses 0-based A[0].
    • Slicing: MATLAB uses 1:10 (inclusive), Python uses 0:10 (exclusive of end).
  • Goal: Import data, process it (like pandas/numpy), and visualize it.

Importing Data: The Modern Way

  • Forget dlmread or csvread. Use modern functions:
  • readmatrix: Best for purely numerical data (like numpy.loadtxt).
    • data = readmatrix('scope_trace.csv');
  • readtable: Best for mixed data (like pandas.read_csv).
    • T = readtable('experiment_log.csv');
    • Access columns by name: T.Voltage (like df['Voltage']).

Data Structures: Structs vs Dicts

  • In Python, you use Dictionaries to group named data:
    • d = {'volts': [1, 2], 'unit': 'V'}
  • In MATLAB, use Structures (struct):
    • data.volts = [1 2];
    • data.unit = 'V';
  • Accessed using dot notation: value = data.volts(1);

Data Structures: Cell Arrays vs Lists

  • In Python, Lists can hold anything: L = [1, 'text', np.array([1])].
  • In MATLAB, standard arrays must be homogeneous (all numbers).
  • Use Cell Arrays (curly braces {}) to store mixed types:
    • C = {1, 'text', [1 2 3]};
    • Access content with curly braces: val = C{1};

Real-World Example: Oscilloscope Data

  • Scenario: You saved a CSV file from a Tektronix scope (tek0001.csv).
  • File Format: Header rows, then Time (Col 1) and Voltage (Col 2).
% 1. Import Data (skipping header automatically)
data = readmatrix('tek0001.csv');

% 2. Extract Columns (NumPy style slicing)
t = data(:, 1); % Time vector
v = data(:, 2); % Voltage vector

% 3. Analyze
v_peak = max(v);
fprintf('Peak Voltage: %.2f V\n', v_peak);

% 4. Visualize
plot(t, v);
xlabel('Time (s)'); ylabel('Voltage (V)');
title('Oscilloscope Capture');
grid on;

Programming Guidelines For Beginners

Overview

  • Procedural programs (Matlab scripts) are like cooking recipes.
  • Even the most complex recipes are composed of elementary steps.
  • You can make your life easier by following some simple guidelines.

Outline:

  1. Visual aspects / Presentation
  2. Organizing your code
  3. Memory and Performance

Basic Visual Aspects

  • Use meaningful file/variable names (within reason).
  • Use spacing and white-space to write clean and easy to parse code.
  • Alignment (within reason).
  • Indentation – Matlab will allow you to break the conventions – Don’t!
  • Take advantage of Matlab editor features like cells and code-folding.

Developing and Organizing Your Code I

  • Assign variables early, make your code easily extendable/adaptable.
  • Go from simple to complex: If you are faced with a complex issue, develop a toy model first.
  • Modular programming: create functions when possible.
    • cleaning up your code
    • creating reusable scripts/functions
    • separating conceptually distinct problems
  • Backup your code, with a meaningful naming conventions (insurance against computer failure).
  • Backup working code before trying out new things (insurance against stupidity).

Developing and Organizing Your Code II

  • Make extensive use of comments!
    • Making your code understandable to others that might use it.
    • And to your future self!
  • Matlab does not necessarily return errors when it does not do what you intended.
    • These are usually the most insidious bugs.
    • Don’t have faith! Always test your code with simple examples.

Memory and Performance

  • Optimizing your code is important for large projects. A very wide topic.
  • But even for smaller projects a few basic guidelines should be followed.
  • Pre-assign arrays and don’t let them grow inside of loops.
  • Avoid loops when possible (are slow), favor matrix algebra.
  • Favor logical operators over the built-in functions “find” and “nonzeros”.
  • Consider using sparse matrices (but sparse indexing is slow).