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:
- use MATLAB to produce line, scatter, surface and contour plots
- add axes labels, titles and legends to the plot axes;
- plot polygons;
- create image plots of pixel data;
- save plots to a file.
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) 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
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. Change the axes
Axis scale
The axis scale can be adjusted using the axis command (help page) 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
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 labels and title
Axis labels and titles can be added to a plot using the xlabel, ylabel and title commands
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. 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). 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.
Exercise 1 - Line Plots
1. Reproduce the plot of
over the domain
shown below. x = linspace(-2 * pi, 2 * pi, 200);
axis([-2 * pi, 2 * pi, -2, 2])
2. Produce a plot of the function
over the domain
. x = linspace(0, 10, 200);
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
. t = linspace(-4, 4, 200);
s = 2 * t .^ 3 + 3 * t .^ 2 - 8 * t + 6;
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., Example 6
Enter the following commands into the code cell below and run the live script.
y1 = x.^2; % first function
y2 = x.^3; % second function
y3 = x.^4; % third function
plot(x, y1, 'r-'); % first plot
plot(x, y2, 'b-'); % second plot
plot(x, y3, 'k-'); % third plot
Adding a legend to a plot
A legend can be added to a plot using the legend command (help page). The placement of the legend can be specified using the Location option
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')
Exercise 2 - Multiple plots on the same axis
4. Reproduce this plot of
and
over the domain
on the same set of axes. x = linspace(-2 * pi, 2 * pi, 100);
axis([ -2*pi, 2*pi, -2, 2 ])
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). Scatterplots
Scatterplots can be produced using the scatter command
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.
x = rand(100, 1); % 100x1 array of random numbers
Exercise 3
6) Reproduce the scatter plot shown below using the values of x and y.
% x and y values - do not delete these
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 ]';
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 ];
plot(x, B(1) + B(2)*x, 'r')
Surface plots
Three-dimensional surface plots can be generated using the surf command (help page). 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. 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)
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);
axis([0, 4*pi, 0, 4*pi, -3, 3])
View angle
With three-dimensional plots we can control the position of the viewpoint using the view command (help page) 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).
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. Exercise 4 - 3D plots
8. Reproduce the surface plot below of the function
over the domain
. [X, Y] = meshgrid(0 : 0.05 : 1, 0 : 0.05 : 1);
Z = exp(-20*((X - 0.5).^2 + (Y - 0.5).^2));
Contour plots
Contour plots show points of equal value can be produced using the contour command (help page) 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);
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);
Z2 = exp(-(X - 1).^2 - (Y - 1).^2);
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.
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. Importing an image file into an array
We can read in an image file into an array using the imread command (help page) 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');
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(i, j) = sqrt((i - 6)^2 + (j - 6)^2);
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');
[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.