Foundations of computer programming in MATLAB — 2D plotting

When plotting in MATLAB, we must first create a figure. This can be created with the figure command, by itself, or we can assign the figure a variable name. For instance, fig_1 = figure; creates a figure and assigns it to variable fig_1. Sometimes we do not care to name the figure and we simply call the command with figure;. MATLAB actually automatically assigns the most recent figure created to the variable name gcf, and sometimes this is all we need.

The plot function

The plot function creates a two-dimensional line plot in a figure. It accepts a variable number of arguments, which can cause some confusion. In its most common form, it is used as follows.

x = 0:0.1:4*pi;
y = sin(x);
figure;
plot(x,y);

This creates a new figure (unnamed) and plots a sine wave for two periods. Usually we use plot in this manner: providing two arguments, one with x-data and the other with y-data of the same length.

Another common syntax is to provide LineSpec parameters to the plot, which change the appearance of the line and data points. For instance, you can change the LineStyle, Color, and Marker with the following.

x = 0:0.1:4*pi;
y = sin(x);
figure;
plot(x,y,...
    'LineStyle','--',...
    'Color','r',...
    'Marker','o'...
);

This syntax works for all the LineSpec properties, such as LineWidth, MarkerSize, and MarkerEdgeColor. A full list of LineSpec properties is available here. These are called name-value pair arguments of plot.

There is a shorthand for the LineSpec properties LineStyle, Color, and Marker. These are so commonly used that a single string input can be used to specify these properties. For instance, we could have written the previous example in the following manner.

x = 0:0.1:4*pi;
y = sin(x);
figure;
plot(x,y,'--ro');

A full list of this shorthand is available here.

More than one plot on the same figure

There are two basic ways to get two plots on the same figure. The most versatile way is to use the hold on and hold off commands. Calling hold on immediately after a plot command allows the next plot command to plot on the same figure. Here’s an example.

x = 0:0.1:4*pi;
y = sin(x);
z = cos(x);
figure;
plot(x,y,'-b');
hold on;
plot(x,z,'-r');
hold off;

We can also use the following syntax to create the same figure.

x = 0:0.1:4*pi;
y = sin(x);
z = cos(x);
figure;
plot(x,y,'-b',x,z,'-r');

This is easier to use, sometimes. However, if you are going to plot n lines on the same plot, we’ll usually use the hold on method.

Limits and labeling of axes

We can easily set the x- and y-limits using the commands xlim and ylim. Each of these commands take a single argument: an array of two values, the first the lower bound, the second the higher bound. Here’s an example.

x = 0:0.1:4*pi;
y = sin(x);
z = cos(x);
figure;
plot(x,y,'-b',x,z,'-r');
xlim([0,4*pi])
ylim([-2,2])

We can also label the axes using the commands xlabel and ylabel. Here’s an example.

x = 0:0.1:4*pi;
y = sin(x);
z = cos(x);
figure;
plot(x,y,'-b',x,z,'-r');
xlim([0,4*pi])
ylim([-2,2])
xlabel('time (s)')
ylabel('amplitude (V)')
title('Some waves, dude')

Notice that we can also place a title on the plot using the title command.

Subplots

Sometimes, we would like multiple plots on the same figure, but not on the same axes. This is usually not useful when we are exporting the figures to be used in a document, but it can be useful for plots we want to see inside of MATLAB, only.

The syntax is simple. The idea is that we can create a two-dimensional array of axes. In the following, we will create a 3 by 2 array of axes.

x = 0:0.02:4*pi;
y = sin(x);
z = cos(x);
figure;
subplot(3,2,1)
plot(x,y,'-b',x,z,'-r');
subplot(3,2,2)
plot(x,y,'-b',x,z,'-r');
subplot(3,2,3)
plot(x,y.^2,'-b',x,z,'-r');
subplot(3,2,4)
plot(x,y,'-b',x,z.^2,'-r');
subplot(3,2,5)
plot(x,y*2,'-b',x,z,'-r');
subplot(3,2,6)
plot(x,y,'-b',x,z*2,'-r');

Legend

A plot legend labels each line on a plot. For a plot with multiple lines, a legend is important. The syntax is easy. Here’s an example.

x = 0:0.1:4*pi;
y = sin(x);
z = cos(x);
figure;
plot(x,y,'-b',x,z,'-r');
legend('sin(x)','cos(x)','Location','SouthEast');

The last two arguments are optional. The default Location is NorthEast.

Exercises

  1. Plot the following expressions on separate figures over a reasonable range of $x$: $x^2$, $e^{-x}$, and $e^{-x}\cos{x}$. Make sure to label all axes and title them.
  2. Plot the following expressions on a single figure over a reasonable range of $x$: $x^1$, $x^2$, and $x^3$. Label everything and create a legend.
  3. Plot the following expressions in a 3 by 1 subplot array for reasonable ranges of $x$: $x^{1/2}$, $x^{1/3}$, and $x^{1/4}$. Label everything.

Histograms

The MATLAB command histogram is the easiest way to make a histogram. Here’s an example.

x = randn(2000,1);
nbins = 30;
h = histogram(x,nbins)

Another variation on this is a histogram of non-numerical values. This can be created using xlabel, but another variation is possible using a categorical vector. Here’s an example.

A = [1 0 0 1 1 0 0 1 1 1 NaN 1 0  NaN 0 0 0 1 1 0 1 1 0 0 0 1 0 1];
C = categorical(A,[1 0 NaN],{'yes','no','undecided'})

Exercise

Use two histograms in a subplot to compare the probability density functions of rand and randn. Generate 1000 values between 0 and 100 and bin them in bins of width 5.

Stem plots

Stem plots connect each data point to the x-axis (typically) via a line. These are quite useful in some cases, especially spectral/Fourier frequency domain analysis. The syntax is straight-forward.

f = 0:pi/10:4*pi;
stem(t,exp(-f).*sin(f))

Polar plots

Polar plots plot a radial coordinate $r$ radially and an angular coordinate $\theta$ angularly.

https://media.giphy.com/media/zjQrmdlR9ZCM/giphy.gif

Here’s an example that may come in handy if you want to get a date. (Just kidding, that is a terrible idea.)

theta = 0:0.01:2*pi;
r = sin(2*theta) .* cos(2*theta);
figure;
polar(theta,r);