3.2. Basic Line Plots¶
MathWorks has prepared a lot of documentation and videos on plotting, so some links to their documentation follows.
Here is an introductory video demonstrating line plotting.
Documentation on 2-D Graph and customize lines.
Documentation on 2-D and 3-D plots.
Documentation on the linespec portion of a plot command.
MathWork’s MATLAB Fundamentals course [FUNDAMENTALS] has a good introduction to creating plots.
3.2.1. Basic Plotting Notes¶
The Plot Tool is easy to use, however, using commands and functions allows for
easier reproduction of plots and more automation. Use the plot(x, y)
function to plot vector y
against vector x
. The number of elements
in x
and y
must be the same.
If only a single vector is passed to plot
, then the index values of the
vector are used for the –axis.
Use an additional argument to the plot
function specifying a color code
to change the color of the data curve. The following command will plot y
versus x in magenta.
>> plot(x, y, 'm')
Some other color codes are:
- 'b' blue
- 'g' green
- 'r' red
- 'c' cyan
- 'k' black
Line style codes are used if you want something other than a solid line. The following command will plot y versus x with a dotted line.
>> plot(x,y,':')
Some other line style codes are:
'-'
solid'--'
dashed'-.'
dash-dot
You can combine these codes. Generally, the order does not matter, so both of the following commands make a plot using a red dotted line.
>> plot(x, y, 'r:')
>> plot(x, y, ':r')
In addition to color and line style, you can specify a marker style. The following command will plot y versus x using asterisks.
>> plot(x,y,'*')
Some other marker style codes are:
- '.' points
- 'o' circles
- 'x' crosses
- '+' plus sign
- 's' square
- 'd' diamond
- '^' upward-pointing triangle
- 'v' downward-pointing triangle
Did you notice that there is no longer a line? If you specify a marker, the
default line style is none. Add a dash (-
) to the marker style to
also plot a line.
The grid
command adds or removes a grid to your plot:
>> grid on
>> grid off
3.2.2. Annotating Plots¶
Labels are added to plots using plot annotation functions such as xlabel
,
ylabel
, and title
. The input to these functions must be text.
Traditionally, the textual data was entered as a character array made with
characters and digits inside a pair of 'apostrophes'
(single quotation
marks). MATLAB now allows text labels that are the newer string arrays made with
characters and digits inside a pair of "quotation marks"
. The text may be
a simple textual constant or be held in a variable. See Text Strings in MATLAB
for more information on textual data.
>> xlabel('Text Label for X-Axis') % a text constant
>> ylabel(yAxisName) % a text variable
If you need more than one line in an axis label or title, use a cell array
created with a pair of curly brackets {}
.
>> title({'first line', 'second line'})
LaTeX markup formatting may be used in the annotations. Thus, x^2
will
become and x_2
becomes . LaTeX markup is a default
standard for mathematical equations. You can search the Internet and find good
documentation on formatting LaTeX math equations. Other symbols, such as Greek
letters, can also be added, such as , , and
. See MATLAB LaTeX support of Greek letters and special characters.
Try the following code to see what happens.
>> xlabel('\sigma \approx e^{\pi/2}')
If you need to use a symbol such as an underscore (_
) or a backslash
(\
) , then preface it with the
escape character \
. Thus, to display \
, you must type \\
.
The MATLAB text
function adds a text annotation to a specified position on the
plot. See the MATLAB documentation for text
.
>> text(3, 5, 'Best result')
3.2.3. Starting a New Plot¶
You may notice your plot being replaced when you enter a new plot command after
making a previous plot. Use the figure
command to keep the previous plot
and start over in a new window.
3.2.4. Multiple Plots in the Same Figure¶
Several small plots may be put in a figure. The subplot(m, n, p) function accomplishes this by making a grid of plots. The variable p is the plot number from 1 to . The plot for the following code is shown in Fig. 3.3.
>> x = linspace(-5, 5);
>> subplot(2, 2, 1), plot(x, x), title('y = x')
>> subplot(2, 2, 2), plot(x, x.^2), title('y = x^2')
>> subplot(2, 2, 3), plot(x, x.^3), title('y = x^3')
>> subplot(2, 2, 4), plot(x, x.^4), title('y = x^4')
With MATLAB release R2019b, enhanced subplots were introduced with
the tiledlayout
function. As with subplot
, a fixed layout
grid of tiled plots is simple to create.
>> tiledlayout(2, 2);
The nexttile
command is used to advance to the next plot.
Several new features were added beyond the capabilities of subplots.
Figures may now have a global
title
,xlabel
, andylabel
for the set of plots.The size and spacing between tiles is adjustable. The following commands reduce the spacing between tiles and the padding between the edges of the figure and the grid of tiles. The net effect is to increase the size of the individual plots.
t = tiledlayout(3, 3); t.TileSpacing = 'compact'; t.Padding = 'compact';Specifying the size and location of tiles can create a custom layout. This is done by passing a tile number and an optional range of tiles to be used to
nexttile
. In the following example, a grid of tiles is created. Then 3 plots are added across the first row. Starting at tile 4, the whole second row is filled with the next plot, which spans a set of tiles. The third row has a single tile plot and a tile plot. This plot, with its simple data, is shown in Fig. 3.4.>> x = linspace(-2,2); >> tiledlayout(3,3) >> nexttile, plot(x,x) >> nexttile, plot(x,x) >> nexttile, plot(x,x) >> nexttile(4, [1 3]), plot(x,x) >> nexttile(7), plot(x,x) >> nexttile(8, [1 2]), plot(x,x)The layout of the plots may be adjusted with each
nexttile
command. This is done with the'flow'
option totiledlayout
. The first plot fills the whole figure. After the second plot, two stacked plots are shown. As each tile is added, the layout of tiles is adjusted to accommodate the new tile. This can make for a nice demonstration showing successive changes to data. Run the code from thesawTooth.m
file to see this. Successive plots show the Fourier series of a sawtooth wave as each new sine wave is added. The user presses theEnter
key when they are ready to see the next plot. The final tiled figure with six plots is shown in Fig. 3.5.Note
Sawtooth wave Fourier Series
The sawtooth wave is a frequently used periodic waveform used in various electrical circuits including music synthesizers. The Fourier series for a sawtooth wave with amplitude of 1 and period of is given by:
% File: sawTooth.m
% Plots of the Fourier series of a sawtooth function
% displayed using a tiledlayout. Each time through
% the loop, a new plot is added.
clear; close all
L = 5;
N = 200;
t = linspace(0, 2*L, N);
s = zeros(1, N);
figure
plt = tiledlayout('flow');
title(plt, 'Sawtooth Fourier Series')
for n = 1:6
nexttile
s = s + sin(2*pi*n*t/L)/n;
f = 0.5 - s/pi;
plot(t, f, 'k', 'LineWidth', 2)
title(['n = ', num2str(n)])
if n < 6
disp('Press enter for next plot')
pause
end
end
3.2.5. Multiple Plots on the Same Axis¶
Visualizations are often be more informative when multiple data sets
are plotted on the same axis. To add new plots onto an existing axis without
replacing the previous plot, use the hold on
command. When you are done
adding plots, issue the hold off
command. Then, unless a new figure is
started, the next plotting command issued will replace what is currently in the
figure.
Another way to plot multiple data sets onto a single axis is to put the –axes values in a matrix. Each column of the matrix will be a different plot. The following simple examples illustrate both methods. See Fig. 3.6 for the plot.
>> x = linspace(0,10);
>> Y = zeros(100,3);
>> Y(:,1) = x;
>> Y(:,2) = 2*x;
>> Y(:,3) = 3*x;
>> plot(x, Y)
>> y1 = x;
>> y2 = 2*x;
>> y3 = 3*x;
>> hold on
>> plot(x, y1, 'k')
>> plot(x, y2, 'k:')
>> plot(x, y3, 'k-.')
>> hold off
>> xlabel('x'), ylabel('y')
>> legend('y = x', 'y = 2x', 'y = 3 x', 'Location', 'northwest')
>> title('Multi-line Plot')
3.2.6. Adding a Plot Legend¶
A legend helps identify what data each plot in the graph correspond to. The
order of legend labels matters – the inputs to legend
should be in the
same order in which the plots were drawn.
legend('first label','second label')
The legend
function also accepts two optional arguments: the keyword
'Location'
and a text description of the location that is given by a
compass direction, such as 'north'
(top center) or 'southwest'
(lower
left). The default location for the legend is 'northeast'
(top right).
legend('Trucks','Cars','Location','west')
3.2.7. 2-D Plot Types¶
MATLAB supports several types of two dimensional plots. Six types of plots other than basic line plots, which we have used in several examples, are described below. Example code to make these plots is also listed below and Fig. 3.7 shows what the plots look like.
-
Scatter Plot
scatter(x, y)
: Scatter plot with variable marker size and color. Example shown in Fig. 3.7 (a).
-
Bar graph
bar(x, y)
: Bar graph (vertical and horizontal). Example shown in Fig. 3.7 (b).
-
Stem plot
stem(x, y)
: A discrete sequence plot – each point is plotted with a marker and a vertical line to the –axis. Example shown in Fig. 3.7 (c).
-
Stair step plot
stairs(x, y)
: The lines on the plot are either horizontal or vertical, resembling the run and rise of stairs. Example shown in Fig. 3.7 (d).
-
Pie chart
pie([0.4 0.3 0.2 0.1], labels)
: The values of the data are passed as a vector that often sums to 1; otherwise, MATLAB will calculate the percentages. The labels of the pie slices should be in a cell array. Example shown in Fig. 3.7 (e).
-
Filled area plot
area(x, [y1; y2])
: Plot multiple data sets with the area between the –axis and each data curve shaded a different color. Each data set is a row of a matrix passed as the data. Example shown in Fig. 3.7 (f).
% File: Plots2D.m
% Some 2-D plotting examples
x = linspace(0, 2, 10);
y = 5 + x.^2;
y2 = 5 + x;
plts = tiledlayout(3, 3);
plts.TileSpacing = 'compact';
plts.Padding = 'compact';
title(plts, '2-D Plots');
nexttile, scatter(x, y, 'ko'), title('(a) Scatter Plot');
nexttile, bar(x, y, 'k'), title('(b) Bar Chart');
nexttile, stem(x, y, 'k'), title('(c) Stem Plot');
nexttile, stairs(x, y, 'k'), title('(d) Stairs Plot');
labels = {'excellent', 'good', 'fair', 'poor'};
nexttile(5, [2 2]), pie([0.4 0.3 0.2 0.1], labels)
title('(e) Pie Chart')
newcolors = [0.7 0.7 0.7; 0.2 0.2 0.2]; % make grayscale
nexttile(7), area(x, [y2; y]'), title('(f) Area Plot');
colororder(newcolors)
3.2.8. Axis Control¶
The axis
command returns a 4 element row vector containing the –
and –axis limits.
>> v = axis
v =
10 20 1 5
Use the functions xlim
and ylim
to set the – and
–axis limits. Both functions take a vector of two elements as
input. For example, the following command sets the lower –axis
limit to 2 and the upper –axis limit to 4.
>> ylim([2 4])
When the lower or upper range of the data falls between the limits that MATLAB
picked, the data may not fill the –axis. Use the axis tight
command to change the limits based on the range of the data.
For plots depicting geometry, we would like the –, –, and
–axes to have the same scale. There are two ways to accomplish this.
The axis
command has an equal
option that sets the scale of each axis
to be the same. We can also set the aspect ratio to be the same for each axis
with the daspect
function, which takes a vector with three values, even for
2-D plots.
>> axis equal % Set the axes scales to be the same
>> % % or
>> daspect([1 1 1]) % Another way to accomplish the same
3.2.9. Tick Marks and Labels¶
MATLAB generally does a good job of setting the tick marks on a plot. The tick labels are by default the numeric values of the tick marks. We sometimes what to change the labels and locations of the tick marks because certain points on the axis have significance. A good example of this is when plotting equations that use trigonometry functions.
The xticks
and yticks
functions take vectors of numeric locations for
the tick marks. The xticklabels
and yticklabels
functions take cell
arrays of textual data. See Text Strings in MATLAB for more information on cell
arrays. The following code illustrates custom tick marks and labels on the
–axis. Notice also that the title uses the texlabel
function
to format strings with LaTeX to match an equation.
The plot is shown in Fig. 3.8.
x = linspace(pi/4, 5*pi/4);
figure, plot(x, 4 - 4*sin(2*x - pi/2))
txt = texlabel('f(x) = 4 - 4*sin(2*x - pi/2)');
title(txt), ylabel('f(x)'), xlabel('x')
xticks(linspace(pi/4, 5*pi/4, 5))
xticklabels({'\pi/4', '\pi/2', '3\pi/4','\pi', '5\pi/4'});
axis tight
3.2.10. Fplots¶
MATLAB includes another 2-D plotting function that comes in handy when working
with either function handles, anonymous functions, or symbolic math functions.
(see Function Handles and Symbolic Differential Equations) The plot, annotations, and
options are the same as with the plot
function that we have used before.
However, instead of passing vectors for the and data, we
give fplot
a function and a range of values for the –axis, or
accept the default –axis range of -5 to 5.
In addition to being convenient when working with function handles or symbolic
math functions, fplot
also correctly handles plotting difficulties, such as
data discontinuities. A good example of this as shown in Fig. 3.9
comes from the trigonometric tangent function.
>> fplot(@(x) tan(x), [0 2*pi])
Note
Now work on The Flight of a Home Run Baseball.