Plots

Plotting data is one of the most important tasks in Matlab programming.  In this section, we will show you how to plot data, modify plots and save your work.

Basic Plot

Here is an example of a plot of a sine wave.  Try to enter the following lines of code into your Matlab Command Window.

Example 1

t = 0:0.1:1;         %Create time vector
x = sin(2*pi*t);     %Create data vector

f = figure;            %Create figure and save handle
h = plot(t, x);        %Plot the data vector against the time vector
xlabel('Time (s)')     %Label the horizontal axis
ylabel('Position (m)')         %Label the vertical axis
title('Position vs. Time')     %Give the plot a title

The first two lines create the vectors that will be plotted.  The third line creates the figure, saving the handle.  The variable f is the figure handle, which can be used to reference the figure later.  The fourth line plots the data, saving the plot handle.  The variable h is the plot handle and can be used to reference and modify the plotted line.  The next three lines all modify the axes, changing the labels and the title.  This example can be used as a template for most basic 2-dimensional plotting tasks.

Features

Multiple Plots on One Axis

Plotting multiple sets of data on the same axes is a useful feature of Matlab.  The hold command allows users to add multiple plots to the same axis.

Example 2

figure
plot(1:10)
hold all
plot(10:-1:1)

The hold on command can be used in place of hold all.  However, if the hold on command is used, then the subsequent plots will be the default blue color with a solid line, unless another color and linestyle are specified.  For this reason, the hold all command is better for most applications.

Multiple Axes on One Figure

There are times when putting multiple axes on the same figure helps to display results more clearly.  The following command breaks the current figure up into m rows and n columns, and creates axes in the pth division.

subplot(m,n,p)

In the following example, a set of axes will be created in the third division of the 2 x 2 area in the figure.  Subplot counts the divisions first along rows from left to right, then along columns from up to down.  This code will create a plot in the upper-right corner of the figure.  Each set of axes has its own properties, labels, title and legend.

Example 3

figure
subplot(2, 2, 3)
plot(1:10)
xlabel('x')
ylabel('y')
title('Subplot 3')

Legend

The legend function in Matlab creates a legend in the current axes of the current figure.  This function is useful for labeling multiple plots on the same axes.

Continuing from Example 2

legend('Positive Slope', 'Negative Slope')

This command will, by default, create a text box in the upper-right corner of the axes that shows both lines and their labels. Sometimes the default placement of the legend interferes with the data in the plot and another location is desirable.

legend('Positive Slope', 'Negative Slope', 'Location', 'NorthWest')

This line of code will place the legend in the upper-left, or ‘NorthWest’, corner of the plot.  The location of the legend can be set by using the ‘Location’ parameter.  The location parameter can either be a 1×4 vector in the format of [left bottom width height], a string indicating a cardinal or intercardinal direction or a string telling Matlab to find the “best” location.    The possible directions are ‘North’, ‘South’, ‘East’, ‘West’, ‘NorthEast’, ‘NorthWest’, ‘SouthEast’ and ‘SouthWest’.  These directions are referenced to ‘North’ at the top-middle of the plot, just like a map.

Grid

The grid function allows a Matlab user to draw vertical and horizontal lines across the plot at intervals specified by the axis tick marks.  The syntax for this command is quite simple.

grid on  %Draws the grid
grid off %Erases the grid
grid     %Toggles the grid on and off, depending on the previous state

Line Properties

Line properties can be modified in two different ways, using the plot command or using the set command.  This section of the tutorial will use code that builds on Example 1.

Colors

This command will allow you to change the color of the plotted line.

set(h, 'Color', 'r');

Alternatively, the line color could have been set in the plot command.

h = plot(t, x, 'r');

Both of these commands will change the color of the line to red.  Colors can be specified in three different ways:  RGB Value, Short Name and Long Name.

[table id=7 /]

Here is a table with all three specifications for eight different colors.  Colors not in this table can be specified with an RGB Value.   The RGB value must be a row vector of three elements, with each element in the range of [0,1].

Linestyle

Different linestyles are useful to change the appearance of your plot or to differentiate between different sets of data.  The linestyle can be changed inside of a plot command or with the set command.

set(h, 'LineStyle', '-.');

or

h = plot(t, x, '-.');

The following table shows the five different linestyles.

[table id=5 /]

Markers

Markers can accomplish the same results as changing the plot’s linestyle.  Markers can also be set with a plot or set command.

set(h, 'Marker', 'o');

or

h = plot(t, x, 'o');

This table shows the fourteen different markers available in Matlab.

[table id=6 /]

Other Properties

Lines have many other parameters including ‘LineWidth’, ‘MarkerFaceColor’, ‘MarkerEdgeColor’ and ‘MarkerSize’.  To see the rest of the properties that belong to a line, use the get command.  To change any property, use the set command.  Type the following command to see all the properties that you can change.

get(h)

To get a single property, type this command.

get(h, PropertyName)

Combining Multiple Property Commands

To set multiple properties at the same time, use a command with the following syntax.

set(h, Prop1, PropVal1, Prop2, PropVal2, ... )

For example, this line of code will create a green dotted line with upward-pointing triangles as markers.

set(h, 'Color', 'g', 'Linestyle', ':', 'Marker', '^') 

However, the same properties can be changed in a plot command with a single string.

h = plot(t, x, 'g:^');

This is a common and useful Matlab shortcut and only works with the Color, Linestyle and Marker properties.  Additionally, these three properties can be in any order within the string.  Other properties can be set inside the plot command.

h = plot(t, x, 'g:^', 'LineWidth', 3);

Try to experiment with the set, get and plot commands to change a variety line properties.

Axis Properties

The axes of a plot are a separate object in Matlab, and can be controlled by using set, get and other commands.  The code in this section will continue using Example 2.

Axis Limits

This code will change the limits of the x-axis to [0,5] and the limits of the y-axis to [2,4]

xlim([0 5])
ylim([2 4])

Ticks

This code will change the locations of the tick marks on the axes.  The parameter gca stands for “get current axes” and will return the handle of the axes of the current figure.

set(gca, 'XTick', [0:pi:3*pi])
set(gca, 'YTick', [1:2:9])

The x-axis should have 4 tick marks at intervals of pi from 0 to 3*pi.  The y-axis should have 5 tick marks at intervals of 2 from 1 to 9.  To check that this is true, see if you can set the limits of the axes back to their original values.

Tick Labels

Tick labels can be set by entering a cell array of strings that will become the tick labels.  Each tick label should correspond to one tick.

set(gca, 'XTickLabel', {'0', '\pi', '2\pi', '3\pi'})
set(gca, 'YTickLabel', {'one', 'three', 'five', 'seven', 'nine')

This code should have set the tick labels on the x-axis to multiples of pi and tick labels on the y-axis to words that correspond to the tick locations.

Saving and Opening Figures

After creating and modifying a plot, saving the figure is often necessary.  Matlab allows users to save figures and to load them later.  The examples in this section will continue from Example 1.

Saving

Figures can be saved either as Matlab figures or as image files.  Both of these commands save the figure from Example 1 as a Matlab figure.

saveas(f, 'example1.fig')

or

saveas(f, 'example1', 'fig')

These commands will save the figure in different formats.

saveas(f, 'example1.jpg')
saveas(f, 'example1.pdf')
saveas(f, 'example1.bmp')

The alternative format can also be used.

saveas(f, 'example1', 'jpg')

Opening

To open a figure, use the openfig command.

g = openfig('example1.fig');

The variable g is the figure handle, which can be used reference the figure.

Summary

This tutorial shows how to create a basic two-dimensional plot and how to use some key features.  There are many topics that this tutorial does not cover; however, any other questions can be answered by using a search engine or by going directly to the Mathworks website.