Line Plots in MATLAB

Tutorial Video

Introduction

This will take you through the basics of performing a 2D Plot in MATLAB.

The figure Function

The function

figure

Will create a new figure using the lowest unused positive integer. e.g. if no additional windows were previously open it will create Figure 1.

If an input argument is selected. e.g.

figure(100)

MATLAB will instead create Figure 100.

If an input argument is selected of a figure that exists. e.g.

figure(1)

Then MATLAB will reselect Figure 1. Any sub-sequential commands will apply to that Figure.

Getting the Data From Excel

Copying Each Column to a New Variable

We have the data we want to plot in an Excel Spreadsheet. Although it is pretty easy to create Variables by typing it in, in MATLAB we will create a new variable call it v and copy the first column to it.

We will then do the same with the second column but this time calling it v:

We can dock Figure(1) by pressing the Dock Button:

I want it snapped to the right of Variables, not below them so I will drag it to the right:

Now the figure is docked:

Since I have x and y data in the form of t and v I can use the plot command:

plot(t,v)

We can also select the Columns we want to plot from a Variable that is a Matrix or alternatively if or input data is in the form of a Table we can select the Table Variables (Columns) to Plot.

Copying All Columns to a New Variable and Selecting which Columns to Plot

If instead of copying the Excel Data to separate Variables t and v, it was copied over as a single Variable vt:

The Command

plot(tv)

Would give:

Note the previous plot in Figure 1 is overridden because Figure 1 is still selected.

In this dataset, no x values were selected so the row index was used for the x values and t and v were plotted with respect to this index.

This isn’t what we wanted, we wanted to plot the first column of vt which is t with respect to the second column of vt which is v. We can explicitly state this in the command:

plot(tv(:,1),tv(:,2))

Making a Table from

For more practice we can also create a table from the columns v and t and plot by selecting the table variables

tabletv=table(t,v)

plot(tabletv.t,table2.v)

tabletv2=table(tv(:,1),tv(:,2))

tabletv2.Properties.VariableNames={'t','v'}

plot(tv2(:,1),tv2(:,2))

Additional Input Arguments

For the Plot Function, many of the additional input arguments come in pairs. The first value selects the setting to be changed and the second value selects the value for such a setting to be changed to. Unlike the names of functions or variables when the inputs are characters, they are not case sensitive.

LineWidth

These input arguments specify the thickness of the line. The first value is a string of characters and the second value is a scalar.

plot(t,v,'LineWidth',5)

Color

This is spelt using English (U.S.). The English (U.K.) spelling will not work.

These input arguments specify the colour of the line. The first value is a string of characters and the second value for primary and secondary colours can either be a string of characters as the full colour name or it’s abbreviation. Alternatively it can be specified as a [R,G,B] value. For this the RGB values are normalised between 0 and 1. In many other applications they range between 0 and 255.

plot(t,v,'Color','Red')

plot(t,v,'Color','R')

plot(t,v,'Color',[1,0,0])

All colours are made from a mixture of three primary colours:

  • red
  • green
  • blue

Black is shown in the absence of these three colours and white is shown when these three colours are at full brightness.

Full NameAbbreviationRGB Value 
'Red''R'[1,0,0]
'Green''G'[0,1,0]
'Blue''B'[0,0,1]
'Magenta''M'[1,0,1]
'Yellow''Y'[1,1,0]
'Cyan''C'[0,1,1]
'Black''K'[0,0,0]
'White''W'[1,1,1]

As seen a colour can be expressed as a [r,g,b] row vector opposed to a pre-existing string.

Many programs such as Microsoft Office list colors in 8 bit, which means they list 2^8=256 levels. If we subtract 1 from 256 to get a 0 value with range from 0-255. We may use the colour pickers in Microsoft Word to determine the colour we want to use. Select the button to change the colour of the text, select More Colours:

Select your colour and then select custom:

You now get your RGB values listed from 0 to 255.

We can create a row vector to it and assign it to a variable name. For instance using the three numbers shown above and dividing them through by 255.

mw_wine=[192/255,0/255,0/255]

Repeating this with the standard colours in Microsoft Word we get:

Custom Variable NameRGB Value
mw_wine[192/255,0/255,0/255]
mw_red[255/255,0/255,0/255]
mw_orange[255/255,192/255,0/255]
mw_yellow[255/255,192/255,11/255]
mw_lime[146/255,208/255,80/255]
mw_green[0/255,176/255,80/255]
mw_sky[3/255,177/255,240/255]
mw_blue[59/255,145/255,207/255]
mw_navy[0/255,32/255,96/255]
mw_purple[114/255,51/255,161/255]
mw_grey[116/255,116/255,116/255]

It is often useful to put these custom colours in a script so you can call this script before plotting to get your desired colour choice.

plot(t,v,'Color',[255/255,192/255,0/255])

Now we can use the Variable Name in place of the RGB row vector:

customcolours

plot(t,v,'Color',mw_orange)

Because we are using a Variable Name opposed to a Character there is no '.

LineWidth

As these input arguments come in pairs. It doesn’t matter if we specify the Color first or the LineWidth first:

plot(t,v,'Color',[255/255,192/255,0/255],'LineWidth',5)

plot(t,v,'LineWidth',5,'Color',[255/255,192/255,0/255])

It can also be helpful using ... to split the code over multiple lines. That way you can easily track the pairs:

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineWidth',5
)

The lines of code above give:

LineStyle

MATLAB also has a number of different types of lines, by default the line is a solid line however another two input arguments can be input to change these:

\displaystyle \begin{array}{*{20}{c}} {\text{Line Style}} & {\text{Specifier}} \\ {\text{solid line}} & \text{-} \\ {\text{dashed line}} & {\text{--}} \\ {\text{dotted line}} & \text{:} \\ {\text{dash-dot line}} & {\text{- }\text{.}} \end{array}

Once again 'LineStyle' and '--' are both strings of characters and must be enclosed in '  '

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle','--',...
'LineWidth',5)

LineStyle 
'-'
'--'
':'
'-.'

Marker

Markers can also be added to the line using two more additional input arguments:

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s'
)

Once again 'Marker' and 's' are both strings of characters and must be enclosed in '  '

MarkerStyle 
'+'
'o'
'*'
'.'
'x'
's'
'd'
'^'
'<'
'>'
'v'
'p'
'h'

MarkerSize

The markers above were quite small, they are hard to read, this can be resolved by using another two additional input arguments:

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20
)

Once again 'MarkerSize' is a string and must be enclosed in '  ' and 20 is a scalar.

MarkerEdge and MarkerFace

The Marker does not need to be the same colour as the line. We can specify both the Edge and the Fill of the marker with another colour using another four input arguments. Once again 'MarkerFace' and 'MarkerEdge' are both strings and must be enclosed in '  '. Each of them has a paired input argument, which uses the same notation as the line color (see above), I will use the [r,g,b] row vector notation.

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20,...
'MarkerEdge',[0/255,176/255,80/255],...
'MarkerFace' ,[112/255,48/255,160/255]
)

Short Hand

For learning pairing the inputs may help for using the plot function but it is quite useful to use the abbreviated notation for some of the most commonly used inputs.

plot(t,v, 'color','b','LineStyle',':','Marker','s')

plot(t,v,'b:s')

Axes

For the axes we use the function set with the input argument gca (get current axes):

set(gca)

Limits

To change the x axis limits the additional input argument 'XLim' in the for of a string  of characters is matched by a 2 by 1 row vector consisting of the upper and lower x limits respectively. Likewise we have the additional input argument 'YLim' matched input argument is a 2 by 1 column vector (if a row vector is input, it will automatically be adjusted) this time consisting of the upper and lower y limits respectively.

set(gca,...,
'XLim',[10,20],...
'YLim',[400,500])

Scale

We can also use the additional input argument 'XLim'  to set the scale on the x axis using the accompanying input argument 'Lin' for Linear (default) or 'Log' for logarithmic scale. For the y scale we use 'YLim'

set(gca,...,
'XLim',[10,20],...
'YLim',[100,500],...
'XScale','Lin',...
'YScale','Log')

FontSize

If we wish to change the Font Size on the axes we can use the additional input argument 'FontSize' followed by a scalar input:

set(gca,...,
'XLim',[10,20],...
'YLim',[100,500],...
'XScale','Lin',...
'YScale','Log',...
'FontSize',20
)

Grid

One can enable the grid by using the function grid with the input argument 'on'
grid('on')

We can have gridlines with minor gridlines using the input argument 'minor'

grid('minor')

One can disable the grid by using the function grid with the input argument 'off'
grid('off')

Because these are commonly used, they also in the form:

grid on

grid minor

grid off

Axis Labels and Title

There are three functions to label the x-axis, y-axis and the figure title these are:

xlabel('time (s)')

ylabel('speed (m/s)')

title('Rocket Projectile')

Note how the brackets enclosed within the '  ' are treated as text and not as part of the code.

If alternatively one has a cell array with the labels, these can also be input as axis labels:

mytestlabels={'test time (s)','test speed (m/s)','Rocket Projectile'}

xlabel(mytestlabels(1))

ylabel(mytestlabels(2))

title(mytestlabels(3))

Legend

The graph is missing a legend we can add one using the following function

legend('Rocket1',...
'Location','NorthWest')

legend('Rocket1',...
'Location','SouthEast')

For the location we use the compass points, these are usually within the chart area but we can also specify for them to be outside.

Location
'North'
'NorthEast'
'East'
'SouthEast'
'South'
'SouthWest'
'West'
'NorthWest'
'West'
'Best'
'NorthOutside'
'EastOutside'
'SouthOutside'
'WestOutside'
'BestOutside'

Hold

So far we have the following code.

figure(1)

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20,...
'MarkerEdge',[0/255,176/255,80/255],...
'MarkerFace' ,[112/255,48/255,160/255]
)

set(gca,...
'XLim',[10,20],...
'YLim',[100,500],...
'FontSize',20
)

xlabel('time (s)')
ylabel('speed (m/s)')
title('Rocket Projectile')

grid('minor')

legend('Rocket1',...
'Location','SouthEast')

This gives us the following:

Now supposing we want to create a plot of v vs t and also a second Rocket that is twice as fast 2*v vs t:

figure(1)

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20,...
'MarkerEdge',[0/255,176/255,80/255],...
'MarkerFace' ,[112/255,48/255,160/255]
)

plot(t,2*v,...
'Color',[192/255,0/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20,...
'MarkerEdge',[0/255,176/255,80/255],...
'MarkerFace' ,[112/255,48/255,160/255]
)

set(gca,...,
'FontSize',20
)

xlabel('time (s)')
ylabel('speed (m/s)')
title('Rocket Projectile')

grid('minor')

legend('Rocket1','Rocket2'...
'Location','SouthEast')

This code overwrites the data on Figure 1 opposed to adding a second Line Plot.

To add additional lines to the Figure 1 opposed to writing over them we need to use the hold function with the input argument 'on'. We should use the hold function with the input argument 'off' to release after we’ve finished plotting.

figure(1)

plot(t,v,...
'Color',[255/255,192/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20,...
'MarkerEdge',[0/255,176/255,80/255],...
'MarkerFace' ,[112/255,48/255,160/255]
)

hold('on')
plot(
t,2*v,...
'Color',[192/255,0/255,0/255],...
'LineStyle',':',...
'LineWidth',5,...
'Marker','s',...
'MarkerSize',20,...
'MarkerEdge',[0/255,176/255,80/255],...
'MarkerFace' ,[112/255,48/255,160/255]
)
hold('off')

set(gca,...,
'FontSize',20
)

xlabel('time (s)')
ylabel('speed (m/s)')
title('Rocket Projectile')

grid('minor')

legend('Rocket1','Rocket2'...
'Location','NorthWest')

Because these are commonly used, there is an abbreviated form:

hold on

hold off

Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.