Linear Algebra and Programming Skills

Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University

Plotting

Learning Outcomes

On successful completion of this page readers will be able to:
MATLAB comes with a number of functions that can be used to plot data. Here we will look at the most common plotting commands.

Line plots

To plot a simple two-dimensional function we can use the plot command (help page)
plot(x co-ordinate array, y co-ordinate array)
where x co-ordinate array and y co-ordinate array are arrays.
Example 1
The MATLAB code below plots the function . Enter it into the code cell below and run the live script.
% Generate co-ordinate arrays
x = linspace(-2, 2, 50);
y = x .^ 2;
 
% Plot figure
plot(x, y)
% Generate co-ordinate arrays
x = linspace(-2, 2, 50);
y = x .^ 2;
 
% Plot figure
plot(x, y)

Plot styles

We can change the appearance of the line by specifying the LineSpec after the co-ordinates in the plot command. The LineSpec is a series of symbols that determine the colour, line style and marker style used.
Example 2
The MATLAB command below plots the function using a red line with circle marking each point (using the previously defined co-ordinate arrays x and y). Enter it into the code cell below and run the live script.
plot(x, y, 'r-o')
plot(x, y, 'r-o')

Change the axes

Axis scale

The axis scale can be adjusted using the axis command (help page)
axis([ xmin, xmax, ymin, ymax ])
where xmin and xmax are the minimum and maximum value along the x-axis (and similar for y). The axis command must come after any plot commands.
There are other axis modes that can be utilised
axis tight % fits axes tightly around data
axis padded % fits axes with a space between the plot and the plot box
axis equal % uses the same length for the data units along each axis
axis square % uses axis lines of equal lengths
axis off % removes axis lines
Example 3
Enter the following command into the code cell below to change the axis limits on the plot from example 3 and run the live script.
axis([ 0, 2, 0, 2 ])
axis([0, 2, 0, 2])

Axis labels and title

Axis labels and titles can be added to a plot using the xlabel, ylabel and title commands
xlabel('x axis label')
ylabel('y axis label')
title('plot title')
Label and title commands must come after any plot commands.
Example 4
Enter the following commands into the code cell below to add axis labels and a title to the plot from example 2 and run the live script.
xlabel('x')
ylabel('y')
title('y = x^2')
plot(x, y, 'r-o')
 
axis padded
xlabel('x')
ylabel('y')
title('y = x^2')

Saving a plot to file

We can save a figure to a file so that we can import it into other documents using the saveas command (help page).
saveas(gcf,filename)
Where filename includes the extension for the image type used. Most common image formats are supported, e.g., png, jpeg, pdf etc., but png (Portable Network Graphics) files are preferred for importing into electronic documents.

Example 5

The command below saves the plot from example 4 as a png file using the filename myplot.png. Enter it into the code cell below and execute it. Check that an image file containing your plot has been produced and open it to see the result.
saveas(gcf,'myfile.png')
saveas(gcf,'myfile.png')

Exercise 1 - Line Plots

1. Reproduce the plot of over the domain shown below.
sinx.png
clear
x = linspace(-2 * pi, 2 * pi, 200);
 
plot(x, sin(x), 'r')
axis([-2 * pi, 2 * pi, -2, 2])
xlabel('x')
ylabel('y')
title('y = sin(x)')
2. Produce a plot of the function over the domain .
clear
x = linspace(0, 10, 200);
y = x.^2 - 3*x + 2;
 
plot(x, y)
 
xlabel('x')
ylabel('y')
3. 3. Produce a plot of the function over the domain using a green line. Scale the s-axis so that it is in the range .
clear
 
t = linspace(-4, 4, 200);
s = 2 * t .^ 3 + 3 * t .^ 2 - 8 * t + 6;
 
plot(t, s, 'g-')
axis([-4, 4, -50, 50])
xlabel('t')
ylabel('s')

Multiple plots on the same axes

Whenever a plot command is used MATLAB will overwrite the previous plot. To suppress this and draw multiple plots on the same axes we use the hold on and hold off commands (help page), e.g.,
plot(x1, y1)
 
hold on
 
plot(x2, y2)
plot(x3, y3)
:
plot(xn, yn)
 
hold off
Example 6
Enter the following commands into the code cell below and run the live script.
x = -2 : 0.1 : 2;
y1 = x.^2; % first function
y2 = x.^3; % second function
y3 = x.^4; % third function
 
plot(x, y1, 'r-') % first plot
hold on
 
plot(x, y2, 'b-') % second plot
plot(x, y3, 'k-') % third plot
hold off
 
xlabel('$x$', 'FontSize', 16, 'Interpreter', 'latex')
ylabel('$y$', 'FontSize', 16, 'Interpreter', 'latex')
x = -2 : 0.1 : 2;
y1 = x.^2; % first function
y2 = x.^3; % second function
y3 = x.^4; % third function
 
plot(x, y1, 'r-'); % first plot
hold on
 
plot(x, y2, 'b-'); % second plot
plot(x, y3, 'k-'); % third plot
hold off
 
xlabel('x')
ylabel('y')

Adding a legend to a plot

A legend can be added to a plot using the legend command (help page).
legend('1st plot label', '2nd plot label', ... )
The placement of the legend can be specified using the Location option
legend('1st plot label', '2nd plot label', ... , 'Location', placement)
where placement is one compass direction from 'north', 'east', 'south', 'west', 'northeast', 'southeast', 'southwest' or 'northwest'.
Example 7
Enter the following commands into the code cell below to add a legend to the plot from example 6 and run the live script.
legend('y = x^2', 'y = x^3', 'y = x^4', 'location', 'southeast')
legend('y = x^2', 'y = x^3', 'y = x^4', 'location', 'southeast')

Exercise 2 - Multiple plots on the same axis

4. Reproduce this plot of and over the domain on the same set of axes.
clear
x = linspace(-2 * pi, 2 * pi, 100);
 
plot(x, sin(x), 'r')
hold on
plot(x, cos(x), 'b--')
hold off
 
axis([ -2*pi, 2*pi, -2, 2 ])
xlabel('x')
ylabel('y')
 
legend('y = sin(x)', 'y = cos(x)', 'Location', 'northwest')
5. The points on a circle centred at with radius r can be calculated using for . Plot four circles centred at with radii . Use axis commands to display the circles in the correct aspect ratio (i.e., they look like circles and not ellipses).
clear
cx = 5;
cy = 5;
theta = 0 : 0.01 : 2*pi;
 
for r = 1 : 4
x = cx + r*cos(theta);
y = cy + r*sin(theta);
plot(x, y, 'b-')
hold on
end
hold off
 
axis([ 0, 10, 0, 10 ])
axis square
 
xlabel('x')
ylabel('y')

Scatterplots

Scatterplots can be produced using the scatter command
scatter(x coordinate array, y coordinate array, marker style)
The marker style is specified using the symbols explained in the Plot styles section.
Example 8
Enter the following commands into the code cell below and run the live script.
clear
x = rand(100, 1); % 100x1 array of random numbers
y = rand(100, 10);
 
scatter(x, y, 'r')
 
xlabel('$x$', 'FontSize', 16, 'Interpreter', 'latex')
ylabel('$y$', 'FontSize', 16, 'Interpreter', 'latex')
clear
x = rand(100, 1); % 100x1 array of random numbers
y = rand(100, 1);
 
scatter(x, y, 'r')
 
xlabel('x')
ylabel('y')

Exercise 3

6) Reproduce the scatter plot shown below using the values of x and y.
% x and y values - do not delete these
clear
x = [ 0.1734, 0.3909, 0.8314, 0.8034, 0.0605, 0.3993, 0.5269, 0.4168, 0.6569, 0.6280 ]';
y = [ 0.0717, 0.1665, 0.7881, 0.5486, 0.0702, 0.2382, 0.3031, 0.2341, 0.4335, 0.4265 ]';
 
scatter(x, y, 'd')
axis([ 0, 1, 0, 1 ])
 
xlabel('x')
ylabel('y')
7. We can calculate a line of best fit for this data using a linear regression model where is the y-intercept and is the slope of the line. To determine and we need to solve the linear system
.
Let , and then we can use the MATLAB command B = X \ Y to solve for B.
Calculate the line of best fit for the data from question 6 and add it to your scatter plot
% Calculate line of best fit
X = [ ones(length(x), 1), x ];
B = X \ y
B = 2×1
-0.0822 0.8394
hold on
plot(x, B(1) + B(2)*x, 'r')
hold off
xlabel('x')
ylabel('y')

Surface plots

Three-dimensional surface plots can be generated using the surf command (help page).
surf(X coordinate matrix, Y coordinate matrix, Z coordinate matrix)
Where the co-ordinate matrix are arrays. To produce a surface plot of the bivariate function we require matrices containing the x and y coordinates of points in the domain. The meshgrid command (help page) is useful for generating these.
[X, Y] = meshgrid(x coordinate array, y coordinate array)
Example 9
The MATLAB commands below generates two element matrices X and Y containing the co-ordinates of points in the domain using an increment of 1 in the x direction and 2 in the y direction. Enter it into the code cell below and run the live script.
[X, Y] = meshgrid(0 : 5, 0 : 2 : 6);
disp(X)
disp(Y)
[X, Y] = meshgrid(0 : 5, 0 : 2 : 6);
disp(X)
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
disp(Y)
0 0 0 0 0 0 2 2 2 2 2 2 4 4 4 4 4 4 6 6 6 6 6 6
Example 10
The MATLAB code below produces a surface plot of the two-dimensional surface over the domain . Enter it into the code cell below and run the live script.
[X, Y] = meshgrid(0 : 0.2 : 4*pi, 0 : 0.2 : 4*pi);
Z = sin(X) + cos(Y);
 
surf(X, Y, Z)
 
axis([ 0, 4*pi, 0, 4*pi, -3, 3 ])
 
xlabel('x')
ylabel('y')
zlabel('z')
[X, Y] = meshgrid(0 : 0.2 : 4*pi, 0 : 0.2 : 4*pi);
Z = sin(X) + cos(Y);
 
surf(X, Y, Z)
 
axis([0, 4*pi, 0, 4*pi, -3, 3])
 
xlabel('x')
ylabel('y')
zlabel('z')

View angle

With three-dimensional plots we can control the position of the viewpoint using the view command (help page)
view(azimuth, elevation)
where azimuth and elevation are the angles (in degrees) that specify the horizontal and vertical position of the viewpoint relative to the centre of view (see diagram below).
azimuth_elevation.jpg
Example 11
The MATLAB command below changes the surface plot produced in example 13 so that it is viewed from the viewpoint with azimuth and elevation . Enter it into the code cell below and run the live script.
view(15, 45)
view(15, 45)

Exercise 4 - 3D plots

8. Reproduce the surface plot below of the function over the domain .
clear
[X, Y] = meshgrid(0 : 0.05 : 1, 0 : 0.05 : 1);
Z = exp(-20*((X - 0.5).^2 + (Y - 0.5).^2));
 
surf(X, Y, Z)
 
xlabel('x')
ylabel('y')
zlabel('z')

Contour plots

Contour plots show points of equal value can be produced using the contour command (help page)
countour(x coordinate matrix, y coordinate matrix, z coordinate matrix)
Example 12
The code produces a contour plot of the same bivariate function used in example 13. Enter it into the code cell below and run the live script.
[X, Y] = meshgrid(0 : 0.1 : 4*pi, 0 : 0.1 : 4*pi);
Z = sin(X) + cos(Y);
 
contour(X, Y, Z)
 
xlabel('x')
ylabel('y')
clear
[X, Y] = meshgrid(0 : 0.1 : 4*pi, 0 : 0.1 : 4*pi);
Z = sin(X) + cos(Y);
 
contour(X, Y, Z)
 
xlabel('x')
ylabel('y')

Exercise 5 - Contour plots

9. Produce a contour plot of the function where and over the domain .
[X, Y] = meshgrid(-2 : 0.1 : 3, -2 : 0.1 : 3);
Z1 = exp(-X.^2 - Y.^2);
Z2 = exp(-(X - 1).^2 - (Y - 1).^2);
Z = (Z1 - Z2).^2;
 
contour(X, Y, Z)
 
xlabel('x')
ylabel('y')

Image plots

Image plots (also known as raster plots) are plots which consist of an array of small squares called pixels. In MATLAB image plots can be produced using the image and imagesc commands.
image(img) % image plot
imagesc(img) % scaled image plot
Where img is an array of pixel data. The image command assumes that the data is formatted so that each pixel has components for the red, green and blue colours for the RGB colour model (known as True Colors - see diagram below).
The imagesc command assumes the data is formatted so that each pixel is represented by a single number (known as Indexed Colors). The colour of each pixel is scaled based on the values in the data array and applied using a colormap.
Example 13
The following commands generate a random array of pixels and plots them using the imagesc command. (the axis equal tight command ensures that the pixels are represented as squares and the vertical axis counts up from the bottom). Enter them into the code cell below and run the live script.
img = rand(10, 10);
 
imagesc(img)
 
axis equal tight
img = rand(10, 10);
 
imagesc(img)
 
axis equal tight

Importing an image file into an array

We can read in an image file into an array using the imread command (help page)
img = imread(filename)
Where filename is the name of the image file. This allows us to perform image manipulation operations on the image. Most common image types such as jpegs, pngs, tifs are supported. The information for the image is stored in the array X which is an where m and n are the number of pixels in the vertical and horizontal direction. Each pixel has 3 values which correspond to the amount of red, green and blue as used in the RGB colour model.
Example 14
Download the file flower.jpg from the Moodle area for this unit and copy to the same folder that this Live Script is stored in. The following commands read in the data for the image file flower.jpg which comes with MATLAB and plots the data using the image command. Enter them into the code cell below and run the live script.
img = imread('flower.jpg');
 
image(img)
 
axis xy equal tight
 
[Nx, Ny, ~] = size(img);
fprintf([ 'The image is made up of %1i pixels in the horizontal direction' ...
'and %1i pixels in the vertical direction.'], Nx, Ny)
img = imread('flower.jpg');
 
image(img)
 
axis xy equal tight
[Nx, Ny, ~] = size(img);
fprintf([ 'The image is made up of %1i pixels in the horizontal direction' ...
'and %1i pixels in the vertical direction.'], Nx, Ny)
The image is made up of 951 pixels in the horizontal directionand 1024 pixels in the vertical direction.

Exercise 6 - Image plots

10. Use two nested for loops to generate an array img where the value of each element is the distance from the centre element, i.e.,
Plot img using the imagesc command.
img = zeros(11, 11);
for i = 1 : 11
for j = 1 : 11
img(i, j) = sqrt((i - 6)^2 + (j - 6)^2);
end
end
 
imagesc(img)
 
axis xy equal tight
11. Download the file central_library.jpg from the Moodle area for this unit and copy to the same folder that this Live Script is stored in. Load the data from this image into an array, determine the number of pixels in the image and plot the image.
img = imread('new_JD_building.jpg');
 
image(img)
 
axis equal tight
[height, width, ~] = size(img);
fprintf('The image has a height of %1i pixels and a width of %1i pixels.', ...
height, width)
The image has a height of 1001 pixels and a width of 1500 pixels.