0% found this document useful (0 votes)
5 views

NoteSet_6_v1

Uploaded by

lianchu517
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

NoteSet_6_v1

Uploaded by

lianchu517
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Dr.

Brett Freidkes University of South Florida

Note Set (NS) #6: Programming Concepts


Plots
Contents
Section 0: Introduction.................................................................................................................................. 1
Section 1: Figures and Plotting ...................................................................................................................... 3
Section 1.1: Figures ................................................................................................................................... 3
Section 1.2: Plots....................................................................................................................................... 5
Section 2: Customization............................................................................................................................. 16
Section 2.1 The Graph’s Axes .................................................................................................................. 16
Section 2.2 Graph Title ............................................................................................................................ 21
Section 2.3 Inside the Coordinate Axes................................................................................................... 22
2.3.1 Data Properties .............................................................................................................................. 22
2.3.2 Legends & Grids ............................................................................................................................. 29
Section 3: Subplots...................................................................................................................................... 32
Section 4: Examples and Exercises .............................................................................................................. 37

Section 0: Introduction

• We have gone through all of the “logical” aspects of this class, i.e., if, while,
and for.

• The remainder of the class will focus on applications of these programming


techniques and various capabilities that MATLAB has to offer.

• The most common (and argumentatively, most important) is the ability to plot
things in MATLAB.
o Note: this is VERY introductory. We are just seeing the tip of the
iceberg with this. There are so many plotting capabilities that we won’t
be able to cover. If you are ever struggling to plot something the way
you want, remind yourself: MATLAB can do it, it’s just a matter of
how. Google is your friend.

• Why do we plot?
o To convey information!

1
Dr. Brett Freidkes University of South Florida

▪ If you have data that you want to share, plots are typically the
best way of explaining that information to others. Quick,
informative, clear.

o To understand simulation results!


▪ You may want to design something, and you run a code that
simulates how it will behave. For example, perhaps a fluid flow
or a cantilever beam (HW#1).
▪ Plots can inform you on what will happen as variables change.

o To troubleshoot your own codes!


▪ Maybe you write a code that calculates the area under a graph
using a Riemann Sum (see NS#5).
▪ We know that the area approximation will improve if we increase
the total number of rectangles.
▪ If you use a plot to confirm this information (like Figure 7 in
NS#5), you can determine if your code has any major errors.

• Figure 1 shows some examples of different figure types (note that these are
from my graduate dissertation...the moral: plotting is used ALL THE TIME).

2
Dr. Brett Freidkes University of South Florida

Figure 1: Several examples of plots, including 2D, 3D, and histograms.

• This document will focus on:


o The plot function: the most common command to use in MATLAB to
plot information.
o Customization of graphs: how do you change colors, line thicknesses,
axes labels, legends, etc.?
▪ Note, the graphs will look lame and bland until this section.

Section 1: Figures and Plotting

Section 1.1: Figures

• Before we jump into plotting, let’s discuss what a figure is and what a plot is.
o A figure is essentially the blank slate that we will be putting plots on.
o A plot is the data/function/etc. that we want to display.

• If you type the word figure into the Command Window (or in the Editor
Window), a blank figure will appear in a new window on screen.

3
Dr. Brett Freidkes University of South Florida

Figure 2: The blank figure panel that appears in a new window after typing figure into MATLAB.

• We can have multiple figures at once on screen, like seen in Figure 3.

o If we try to plot something, MATLAB will put that plot on the “active”
figure, which is the one that you clicked last.

o In Figure 3, we can see that Figure 2 is the active plot since on the top-
left corner of the window, its text is darker than the other figure (see the
content inside the blue boxes).
▪ Note that to avoid confusion, I will bold MATLAB figures and
leave the unbolded text referring to the figures in this specific
Note Set document.

4
Dr. Brett Freidkes University of South Florida

Figure 3: Two figure panels on screen at the same time. Note that Figure 2 is currently the "active" figure since its label is darker
than the label of Figure 1 (see the blue boxes).

• If you wanted to close a figure, you could x-out (of course), but you can also
type close into the Command Window.
o This will close the active figure.
• If you want to close ALL the figures, you can type close all and it will exit all
the open figure windows.

• If you want to copy/paste a figure, go to the menu options in the figure window
and go to:
o Edit → Copy Figure
o This command will take the figure exactly as it currently is and allow
you to paste it in other places.
▪ “Currently is” implies the size, formatting, etc. will be
copy/pasted.
• You can also save figures as .fig files if you go to:
o File → Save (or Save As...)
o The way that the figure currently is (i.e., formatting, size, etc.) will be
saved on your computer. You can then open that figure exactly as you
had left it.

Section 1.2: Plots

5
Dr. Brett Freidkes University of South Florida

• The command plot will plot a series of points and connect the dots inside a
figure window.
o For example, imagine we want to plot a line that is composed of two
points: (0,2) and (1,3).
o The x-values are 0 and 1.
o The y-values are 2 and 3.

o The way that plot works is that you will provide it a vector (i.e., a one-
dimensional matrix) of x-values and a vector of y-values.
▪ The x-vector is inputted first and the y-vector is inputted second.

o It will then plot the line that connects those points.


o Figure 4 shows the results of this simple plot.

% Plotting (0,2) and (1,3)


x = [0 1]; %x-values of 0 and 1
y = [2 3]; %corresponding y-values of 2 and 3
plot(x,y)

Figure 4: Plot containing points (0,2) and (1,3). A line is drawn between the two points.

• Important note: the points themselves aren’t plotted (meaning you can’t see
circles or anything). You only see the line connecting them.
o We will discuss how to do this later in this document.

6
Dr. Brett Freidkes University of South Florida

• Another note: you can write the matrix directly into the plot command as
shown below.

plot([0 1], [2 3]) %also works

Example #1: Several Points

• Let’s say Table 1 shows data that needs to be plotted.


Table 1: Data from an experiment.

time 1 4 6 7 10
voltage -1 -4 10 4 1

• Using the plot command and assuming that time is on the x-axis (voltage is
on the y-axis), we will draw a line connecting the points. This is shown in
Figure 5.

Figure 5: Data seen in Table 1 plotted, i.e., (1,-1), (4, -4), (6, 10), (7,4), and (10,1)

time = [1 4 6 7 10]; %time data points


voltage = [-1 -4 10 4 1]; %voltage data points
plot(time,voltage)

• Note! The order that you organize the points in your vector MATTERS. Let’s
say we take the same data but we switch the 2nd and 3rd points (highlighted in
Table 2 below).

7
Dr. Brett Freidkes University of South Florida

o Figure 6 shows this. MATLAB does not make assumptions for what
you want, i.e., it does not assume you want a plot perfectly from
left-to-right.
Table 2: Data from an experiment.

time 1 6 4 7 10
voltage -1 10 -4 4 1

time = [1 6 4 7 10];
voltage = [-1 10 -4 4 1];
plot(time, voltage)

Figure 6: Same data from Table 1, but we flipped the 2nd and 3rd data point. MATLAB does not assume you want the plot to be
entirely from left-to-right.

Example #2: Plotting a Function

• Let’s try to plot a function like 𝑦 = 𝑥 2


• The general game plan is that you need two vectors to plot: one for the x-axis
and for the y-axis.
o For the x-axis, let’s leverage the colon operator to set up a simple list
from 0 to 9 in increments of 3.
o Our x-vector will be [0 3 6 9].

x = 0:3:9; %[0 3 6 9]

8
Dr. Brett Freidkes University of South Florida

• To find our y-values at each of those points, we want to square each one
individually.
o The easiest way to do that is to use the dot operator, which will perform
element-by-element operations on a matrix.

x = 0:3:9; %[0 3 6 9]
y = x.^2 %dot operator to create [0 9 36 81]

• At this point, we have two vectors of equal length that can be plotted against
each other.
o If they weren’t equal length, MATLAB will give an error!

• Plotting yields Figure 7.

x = 0:3:9; %[0 3 6 9]
y = x.^2 %dot operator to create [0 9 36 81]
plot(x,y)

Figure 7: The function y = x2 plotted in MATLAB with only 4 data points.

• The graph above doesn’t really look that smooth.

9
Dr. Brett Freidkes University of South Florida

o The reason is because MATLAB is drawing a line between all of the


points. How do you think we can improve the graph so it looks more
curvy/parabolic?

• If we refine the x-vector so that it has more values, we can evaluate the graph
at more points and create a smoother curve. Figure 8 shows this.

Figure 8: Smoother graph since the x-vector increment was reduced from 3 to 0.01. More data points = smaller lines connecting
points = smoother curve.

Hold

• What if you want to plot multiple functions on the same figure?


o Perhaps for comparing multiple sets of results.

• This is where the command hold comes in.


o The word hold is basically a way to tell MATLAB whether to “keep
holding the current plot in the figure” or to “overwrite the data in the
current plot with the new data.”

• If you type hold on in the code, MATLAB knows to keep the previous data
set.
o If you type hold off, it will assume that you do NOT want the previous
data set in the figure.

10
Dr. Brett Freidkes University of South Florida

• Below shows an example of the two previous plots of 𝑦 = 𝑥 2 , where we used


the hold on command to keep the first data in order to compare the smoother
curve to it.
o Note that MATLAB will use different colors if hold on is used to
differentiate between graphs.
o We will discuss colors/legends/customization later in this document.

x = 0:3:9; %[0 0.01 0.02...8.99 9]


y = x.^2;
plot(x,y)
hold on %this tells MATLAB to keep the first data set

x = 0:0.01:9; %[0 0.01 0.02...8.99 9]


y = x.^2;
plot(x,y)

Figure 9: The red curve is the smoother data set from Figure 8, while the blue curve is the function only evaluated at 4 data
points. Using hold, we can compare them.

• Regarding the variables used above, we could easily change the variable
names to something like x1, y1, x2, and y2 to keep all the data as separate
terms.
o If you choose to recycle the same variables, the first plot remains
unaffected since it is ALREADY in the figure panel...we will just
overwrite the values of x and y in the Workspace.

11
Dr. Brett Freidkes University of South Florida

Example #3: For Loops

• The function 𝑦 = 𝑚𝑥 is a line with a slope m.


o Maybe we want to plot several lines with various slopes in order to see
how the value of m changes the behavior of the graph.

• In the code below, we will use a for loop to compare lines of different slopes
from x = 0 to x = 3.
o The variable x is defined before the loop and tells us which values on
the x-axis to evaluate the different functions at.
o The for loop cycles through slopes of 1:4
▪ So, on the first iteration of the loop, m (the slope) is 1.
▪ On the next iteration, m is 2
▪ And so on...

o Within a loop, we will find y, which will be the slope for that loop
iteration multiplied by the vector x.
▪ Note that y will be the same length as x
▪ We do not need a dot operator to multiply m and x since m is a
constant (only need the dot for multiplying matrices and doing
element-by-element operations).

o Because we wrote hold on, the graphs will be plotted on top of each
other.

Figure 10: Using a for loop to plot various curves on top of each other.

12
Dr. Brett Freidkes University of South Florida

x = 0:0.01:3; %x-values

for m = 1:4 % [1 2 3 4], slope values


y = m*x; % y = m*[0 0.01 0.02...2.99 3]
plot(x,y)
hold on
end

▪ Let’s redo the same exact problem but using a different method for coding.
o This time, we defined a vector m before the for loop, m = [1 2 3 4].
o We will run the for loop for the correct number of times (since
1:length(m) is 1:4).
o Then, based on the value of ii, we will call the particular value of m out.
▪ For example, ii is initially 1 once the for loop starts, so m(1)
means the first element in the m vector (this happens to be equal
to 1).
▪ We multiply m(ii) by x to give y and plot
▪ Then, ii becomes 2 and we access m(ii) = m(2) (which happens
to be equal to 2).
▪ This continues for each element in the m matrix.

X = 0:0.01:3;
m = 1:4;

for ii = 1:length(m)
y = m(ii)*x; %this picks the iith element in the m vector
plot(x,y)
hold on
end

• Okay, so what’s the point?


o If m had random values (not in any sort of pattern with a constant
increment), then this technique is required. Below shows an example
where we want many slope values that are decimals.
o Figure 11 presents the results of this code.

13
Dr. Brett Freidkes University of South Florida

x = 0:0.01:3;
m = [4 -1 2 3.5]; %length of 4

for ii = 1:length(m) %1:4


y = m(ii)*x; %this will pick the iith element in the m vector
plot(x,y)
hold on
end

Figure 11: Lines from x = 0 to x = 3 with slopes of 4, -1, 2, and 3.5.

linspace

• In NS#5, we introduced the concept of generating a list of numbers using the


colon. This is based on:
o The starting number
o The increment
o The ending number
• We are unable to control how many numbers there are easily (you can think
ahead, of course, but what if you didn’t want to?)

• Another list generator is linspace, which will create a list with “linear
spacing” between points.
o The difference between this and the colon operator is that we can set
how many points we want without specifying the increment. We need:

14
Dr. Brett Freidkes University of South Florida

▪ The starting number


▪ The ending number
▪ How many points you want in between.

o Figure 12 shows the syntax for the linspace command.

Figure 12: The function linspace.

• This will ensure that you have the specified number of points, where the
distance between points is constant.
o This specified number of points N includes the starting and ending
points.
o If the number of points is left blank, then MATLAB defaults to a value
of 100 (the fifth example in Table 3).
o Note that if the number of points desired is 1 (the last line in Table 3
below), MATLAB defaults that value to the ending point.
▪ If you type help linspace into the Command Window, you will
see the description and defaults of the table.

• Note: linspace and the colon operator basically do the same exact thing, just
in different ways.
Table 3: Examples of using linspace.

linspace(x1,x2,N) Output
linspace(0,1,2) [0 1]
linspace(0,1,3) [0 0.5 1]
linspace(0,1,4) [0 0.3333 0.6666 1]
linspace(10,20,6) [10 12 14 16 18 20]
linspace(1,100) [1 2 3...98 99 100]
linspace(0,150,1) 150

15
Dr. Brett Freidkes University of South Florida

Section 2: Customization

• We now have a general understanding of how to use the plot function. But the
previous examples in this document are not appealing to look at.
• This section discusses how to improve the graphs, both from a cosmetic
perspective and a technical one.

• First, Figure 13 shows the general layout of a figure. We will discuss how to
alter these items individually in the coming subsections.

Figure 13: A description of different parameters that change the look of your graph. Image taken from Kaw, Chapter 3.

Section 2.1 The Graph’s Axes

• First, every graph should ALWAYS have axes labels.


o In the previous figures in this document, they were left off, so the graph
was as minimal as possible (this is initially how MATLAB presents the
information).
o From here on out though, every graph should be labeled so the reader
knows what information you are displaying.

16
Dr. Brett Freidkes University of South Florida

Figure 14: The figure from Example #1 with the appropriate axis labels now.

• To create labels, you simply type xlabel() and ylabel() with the text inside of
the command.
o Use single quotations (apostrophes) just like we do when we use disp
or fprintf.
• The code for plotting Figure 14 is shown below.

time = [1 4 6 7 10]; %time data points


voltage = [-1 -4 10 4 1]; %voltage data points
plot(time,voltage)
xlabel('Time, t [s]') %x-axis label
ylabel('Voltage, V [volts]') %y-axis label

• What if we want to change the range of the axis numbers? For example,
instead of going from 1 to 10 on the x-axis, maybe I want to go from 2 to 6.
o Additionally, maybe I want to change the -4 to 10 on the y-axis to -3
to 8.

• This requires the xlim() and ylim() command, which is basically setting up
the lower and upper limits of the graph.

17
Dr. Brett Freidkes University of South Florida

time = [1 4 6 7 10]; %time data points


voltage = [-1 -4 10 4 1]; %voltage data points
plot(time,voltage)
xlabel('Time, t [s]')
ylabel('Voltage, V [volts]')
xlim([2 6]) %lower limit of 2, upper limit of 6
ylim([-3 8]) %lower limit of -3, upper limit of 8

• Figure 15 shows the result of the code above.


o This may be useful to emphasize certain regions of a graph or ignore
regions that aren’t important
o May also be useful to investigate things for yourself (strange
discontinuities, for example)

Figure 15: Using xlim and ylim, we can change the upper/lower limits of each axis.

• Okay, what else can we do to the axes?


o How about the ticks, i.e., the numbers in between the lower and upper
limits?
▪ Maybe we want more or less ticks?
▪ Different increments?
▪ What about the way the ticks are presented?

• There are two commands we will look at:


o xticks & yticks
o xticklabels & yticklabels

18
Dr. Brett Freidkes University of South Florida

• First, xticks and yticks both change the ticks that are visible on the graph.
o Figure 16 shows this based on the code below.
o Note that we removed the xlim and ylim commands added prior so we
can see all the data this time.
• Like most other things in MATLAB, this requires brackets within the
parentheses to group a list of numbers.

time = [1 4 6 7 10]; %time data points


voltage = [-1 -4 10 4 1]; %voltage data points
plot(time,voltage)
xlabel('Time, t [s]')
ylabel('Voltage, V [volts]')
xticks([1 5 8 10]) %tick values on the x-axis
yticks([-4 0 4 10]) %tick values on the y-axis

Figure 16: Using xticks([1 5 8 10]) and yticks([-4 0 4 10]), we create the plot above.

• We’re making progress...what if we don’t want the numbers showing but


something else custom?
o For example, maybe we want to graph a sine wave as a function of
radians. We may want to actually write “π” instead of using a tick at
3.14159....
• This is where xticklabels and yticklabels comes in.
o Below shows a graph with random labels we typed in and the code
below.
19
Dr. Brett Freidkes University of South Florida

o With text, we will use curly brackets to enclose the group of custom
labels.
o These labels will correspond with the ticks that were specified on the
axis using the xticks and yticks commands earlier in the code.

time = [1 4 6 7 10]; %time data points


voltage = [-1 -4 10 4 1]; %voltage data points
plot(time,voltage)
xlabel('Time, t [s]')
ylabel('Voltage, V [volts]')
xticks([1 5 8 10])
yticks([-4 0 4 10])
xticklabels({'one','five','eight','ten'})
yticklabels({'hi','hello','yes','whatsup'})

Figure 17: Custom labels on the ticks using xticklabels and yticklabels.

• What about the font size of the axis, including the labels and the ticks?
o I typically make all my font sizes 14...just a recommendation.

• First, we can add other inputs into the xlabel and ylabel commands.
o We will separate using a comma and then use apostrophes to tell
MATLAB what we’re trying to alter. Then, provide the number so it
knows.

xlabel('Time, t [s]','fontsize',14)
ylabel('Voltage, V [volts]','fontsize',14)

20
Dr. Brett Freidkes University of South Florida

• Note that there are LOADS of properties you can change like this. MATLAB’s
documentation on their website discusses a lot of them, like changing the font
type, boldness, color, etc.

• The last one I want to discuss is changing properties of the graph coordinate
axes themselves.
o The axes themselves are referred to in MATLAB as gca (standing for
“graph coordinate axes”).

• A command like set() can change a property of the coordinate axes, like the
font size. Below is the command I most often use to get the graph looking
more appealing.

set(gca,'fontsize',14) %set graph coordinate axes font to 14

• Figure 18 shows the result of implementing these changes, where the font size
of the ticks, labels, etc. are much easier to read.
o Compare this figure to Figure 5...much better, no?

Figure 18: The graph after changing the label and gca sizes.

Section 2.2 Graph Title

• This is straightforward...if you want to title your graph, you can use the
title() command and type the label that will go above the graph.

21
Dr. Brett Freidkes University of South Florida

o You can also use the same types of commands we did with the labels
described earlier.

Figure 19: Including a title.

time = [1 4 6 7 10]; %time data points


voltage = [-1 -4 10 4 1]; %voltage data points
plot(time,voltage)
xlabel('Time, t [s]','fontsize',14)
ylabel('Voltage, V [volts]','fontsize',14)
set(gca,'fontsize',14) %set graph coordinate axes font to 14
title('Sensor Voltage','fontsize',14)

Section 2.3 Inside the Coordinate Axes

• Now that we are done addressing the outer portions of the figure, let’s move
inwards. We will discuss:
o The data itself
o Legends
o Grids

2.3.1 Data Properties

• The general syntax for changing properties is to type the property of interest
and then the value/type for that property.

22
Dr. Brett Freidkes University of South Florida

o This is shown generally in Figure 20, where we will type the property
(examples: ‘LineStyle’, ‘MarkerSize’, ‘Color’, etc.) and then the
corresponding value for what we want.
o If this “value” is text (like what color we want), then we use single
apostrophes as well.
o If the “value” is a number, we just write the number without
apostrophes.

Figure 20: General format for accessing a property and then changing it to a specified value.

• Properties that you can change about the line you plot:
o Color
o Markers (and their properties)
o Line type and thickness

• If you want to change properties of a line that you plotted, you can do so in
the plot command itself.
o First, the color: we can do this in 3 different ways, all shown below.

o 1) Type the property ‘color’ after the x and y inputs. Then, type one of
the predefined colors in MATLAB (you can see these in Figure 21).
▪ Each predefined color has a letter associated with it as seen in
Figure 21...you can just type that as well.

o 2) You can remove the property title ‘color’ if you are using a
predefined color. Just include the color name immediately after the x
and y inputs.

o 3) Using an RGB matrix. Colors are defined using combinations of


red, green, and blue. We can create any arbitrary color we want by
varying the values of the red, green, and blue elements in a matrix
(between 0 and 1).

23
Dr. Brett Freidkes University of South Florida

▪ For example, the numbers in a matrix variable correspond with


red, green, and blue in that order.
▪ If I write [0 0 1], that means we want a plot that is entirely blue
(since [0 0 1] = [red green blue]).

plot(time,voltage,'color','blue') %specifying the color


plot(time,voltage,'color','b') %specifying the color

plot(time, voltage, 'blue')


plot(time, voltage, 'b') %shorthand without the word color

rgb_variable = [0 0 1] %red/green/blue from 0 to 1...all blue


plot(time, voltage, 'color',rgb_variable) %using color matrix

Figure 21: Predefined colors, markers, and line styles.

---------------------------------------------------------------------------------------------------

• Next, what are markers? Remember earlier when I said that we can only draw
lines when using the default plot function and not show the data points
themselves?
o Markers are those data points!

• The second column in Figure 21 shows different types of markers you can use
to represent your data points.
o This includes circles, stars, squares, etc.

• Like colors, there are a few ways of adding markers.


24
Dr. Brett Freidkes University of South Florida

o First, you can write the property ‘Marker’ followed by the


corresponding, predefined symbol.
o The data below is an example that produces the left side of Figure 22.

x = 0:0.1:10;
y = sin(x);
plot(x, y, 'Marker','o') %using circles as markers
xlabel('x-axis','fontsize',14)
ylabel('y-axis','fontsize',14)
set(gca,'fontsize',14)

• If you don’t specify the property ‘Marker’ in the plot command, then
MATLAB will think you ONLY want the dots and no lines.
o Essentially, when editing the ‘Marker’ property, you are accessing the
properties of the marker on the line. If you don’t access the property
of the line, it will assume that there is no line.
o The case with just markers is

Figure 22: plot(x,y,'Marker','o') (left) versus plot(x,y,’o’) (right). There is no line connecting the dots in the right figure.

• Other properties that you can change about the markers besides which shape
they are include:
o The Marker Size
o The Marker Face Color
o The Marker Edge Color

• Figure 23 shows how changing the marker properties may change the
appearance of your graph.

25
Dr. Brett Freidkes University of South Florida

Figure 23: Different MarkerSize and MarkerFaceColor properties...not affiliated with the code above

• Below shows all three properties being changed in one line of code.
o We consistently list properties one after another.
o Note that the first property, the marker type, didn’t have the ‘Marker’
command before it like we discussed above (so we will have just
upwards arrows as the markers, no line).
• Figure 24 shows the output of the code below.

x = 0:0.1:10;
y = sin(x);
plot(x,y,'s','MarkerSize',10,'MarkerEdgeColor','r','MarkerFaceColor','g')
xlabel('Time, t [s]')
ylabel('Voltage, V [volts]')
set(gca,'fontsize',14)

Figure 24: Marker properties corresponding with code above.

--------------------------------------------------------------------------------------------------

26
Dr. Brett Freidkes University of South Florida

• The last property we need to investigate is the line style and width.
o The type of line corresponds with the third column in Figure 21.
o Like the other properties, we type the characteristic we want to
specify after the x and y inputs.

x = 0:0.1:10;
y = sqrt(x);
plot(x,y,'LineStyle','--') %dashed line

• The code above produces Figure 25, where the line is now dashed (see in
Figure 21 how the dashed line corresponds with the symbol -- ).

Figure 25: Changing line styles.

• What about the line width (thickness)?


o First off, I always recommend making this property thicker. Why? If it
is too thin, it is hard to read.
o The code below creates Figure 26, where we have three curves of
varying widths.

x = 0:0.1:10;
y = sqrt(x);
plot(x,y,'b','LineWidth',0.5)
hold on
plot(x,2*y,'r','LineWidth',2)
plot(x,3*y,'k','LineWidth',3.3)
xlabel('x')
ylabel('y')
set(gca,'fontsize',14) %set graph coordinate axes font to 14

27
Dr. Brett Freidkes University of South Florida

Figure 26: Varying line widths.

• You can also change the style of the line using the third column in Figure 21.
o Same procedure as before: we include the property after the x- and y-
inputs and then specify it to the value we want.
o This is exemplified below and in Figure 27.

x = 0:0.1:3;
y = exp(x);
plot(x,y,'k','LineStyle','--')
hold on
plot(x,2*y,'r','LineStyle',':')
plot(x,3*y,'b','LineStyle','-.')
set(gca,'fontsize',14)

Figure 27: Different line styles.

28
Dr. Brett Freidkes University of South Florida

• The shorthand version of changing a line: you can change the three
properties in one command.
o Referencing Figure 21, properties include color, marker type, and line
style in that order (order of the columns).
o Since these are the most common to change, MATLAB allows you to
change them in one go.
o The code below shows an example that produces Figure 28.

x = 0:0.1:3;
y = log10(x); %log, base-10
plot(x,y,'rs--') %red, squares, dashed
hold on
plot(x,2*y,'b*:') %blue, stars, dotted
xlabel('x','fontsize',14)
ylabel('y','fontsize',14)
set(gca,'fontsize',14)

Figure 28: Comparing different colors, marker types, and line style in one command.

2.3.2 Legends & Grids

• Legends are important for distinguishing different data sets on the same
figure.
o The legend command allows you to type text in the order that the
plots are created.
o In the code below, we plot y1 first…that means that the first spot in
the legend will correspond with this graph (i.e., the style in the legend
matches the style in the figure).

29
Dr. Brett Freidkes University of South Florida

x = 0:0.01:8;
y1 = sin(x);
y2 = sin(x-pi/4);
plot(x,y1,'r','linewidth',2)
hold on
plot(x,y2,'b','linewidth',2)
xlabel('Time, t [s]','fontsize',14)
ylabel('Pressure, P [Pa]','fontsize',14)
set(gca,'fontsize',14)
legend('Sensor #1','Sensor #2','fontsize',14)

Figure 29: Graph with a legend now.

• Lastly, we could include a grid for reading convenience by just typing the
command grid on in the code. Below shows the same graph as above with a
grid.

Figure 30: Graph with a grid.

30
Dr. Brett Freidkes University of South Florida

What if you forget everything?

• There is the convenience of your code running and all the properties do
exactly what you want! That’s the benefit of having the commands above
known.
• However, if you are making a plot for a one-time purpose, you may want to
edit it accordingly. You can use the figure window itself to do this.
o At the top of the figure is an icon to open the Property Inspector (see
Figure 31).

Figure 31: Property inspector to change properties without using code.

• Figure 32 shows the Property Inspector opened.


o If you click a line on the graph, the ability to edit the line will show up
in the Inspector window.
o Mess around with this! It’s very useful!!

Figure 32: Property Inspector opened.

31
Dr. Brett Freidkes University of South Florida

Section 3: Subplots

• There are instances where you may want two graphs to be plotted near each
other, but not on the same set of axes (because of varying units, for example).
• This is where the concept of subplot comes in.
• Figure 33 shows an example of a subplot, where 2 graphs are included.
o The top graph shows the height of a tree as a function of time.
o The bottom graph shows how many apples that tree produces as a
function of time.
o We can compare the two graphs and gain information about their
relationship (for example, when the tree is 30 years old, it’s above 100
inches tall and produces near 100 apples).

Figure 33: Subplot example, where we see two separate axes and two separate curves

• So, how do we create this type of thing?


o We use the subplot command, which is shown in Figure 34.
o We specify the number of rows and columns we want for our grid of
plots.
o Then, we choose the graph we want to edit.
▪ Graph 1 is row 1, column 1.
▪ Graph numbers are ordered as if we are reading in English: left-
to-right and then jump to the next line. Figure 35 shows this.

32
Dr. Brett Freidkes University of South Florida

Figure 34: The subplot command.

Figure 35: Subplot grid, where the numbers represent the graphs we may want to edit.

Example

• Let’s plot a function from 0 to 5 using 1000 points and the area under its
curve as a function of x.
o We will do a 2x1 subplot, where the top plot is the function and the
bottom is the integration.

𝑓(𝑥) = 𝑥 2
𝑥
1
𝑎𝑟𝑒𝑎 = ∫ 𝑥 2 𝑑𝑥 = 𝑥 3
0 3

• First, we create our variables.


o For x, since we know how many points we want, we will use
linspace.

33
Dr. Brett Freidkes University of South Florida

x = linspace(0,5,1000); %0 to 5, 1000 points


f = x.^2; %f(x),dot used to square each term in matrix
area = 1/3*x.^3; %area

• Then, we want to make our first plot.


o We use the subplot command, where we specify the general shape of
our grid and then activate graph #1.

x = linspace(0,5,1000); %0 to 5, 1000 points


f = x.^2; %f(x),dot used to square each term in matrix
area = 1/3*x.^3; %area
subplot(2,1,1) %2 rows, 1 column. Graph #1
plot(x,f,'b','linewidth',2) %plotting on active graph (#1)
• After this, we see the plot in Figure 36.
o An array has been created, but the 2nd plot hasn’t been generated yet.

Figure 36: Result after partial code.

• Then, we want to plot the area as a function of x, which is on Graph #2. We


see that we activated this in the code below.

34
Dr. Brett Freidkes University of South Florida

x = linspace(0,5,1000); %0 to 5, 1000 points


f = x.^2; %f(x),dot used to square each term in matrix
area = 1/3*x.^3; %area
subplot(2,1,1) %2 rows, 1 column. Graph #1
plot(x,f,'b','linewidth',2) %plotting on active graph (#1)
subplot(2,1,2) %Graph #2 is now active
plot(x,area,'r','linewidth',2) %plotting on graph #2

Figure 37: After most recent code, we activated Graph #2 and plotted.

• Okay, but this isn’t helpful, we need axes!


o We do this in the same way as before, except we ensure that the axes
are being attached to the active graph.

35
Dr. Brett Freidkes University of South Florida

x = linspace(0,5,1000); %0 to 5, 1000 points


f = x.^2; %f(x),dot used to square each term in matrix
area = 1/3*x.^3; %area

subplot(2,1,1) %2 rows, 1 column. Graph #1


plot(x,f,'b','linewidth',2) %plotting on active graph (#1)
xlabel('x','fontsize',14) %on graph #1, since that's active
ylabel('f(x)','fontsize',14)

subplot(2,1,2) %graph #2 is now active


plot(x,area,'r','linewidth',2) %plotting on graph (#2)
xlabel('x','fontsize',14) %on graph #2, since that's active
ylabel('Area','fontsize',14)

Figure 38: Final subplots from the example.

36
Dr. Brett Freidkes University of South Florida

Section 4: Examples and Exercises

1) Which of the following is equivalent to 1:0.5:2?

a) linspace(1,0.5,2)
b) linspace(1,3,2)
c) linspace(1,2,2)
d) linspace(1,2,3)
e) linspace(1,0.5,3)

2) The plot below corresponds with which command?

a) plot([1 2], [5 6])


b) plot([1 2], [2 3])
c) plot([2 6], [1 5])
d) plot([1 5], [2 6])
e) plot([2 5], [1 6])

3) What color would the plot be if the following code was used?

co = [0 1 0];
plot(x,y,'color',co)

a) Black
b) Green
c) Red
d) White
e) Blue

37
Dr. Brett Freidkes University of South Florida

4) How many data sets will be shown in the plot created from the code below?

x = 0:0.01:5;
y = x.^3+1;
plot(x,y)
plot(x,2*y)
hold on
plot(x,3*y)
hold off
plot(x,4*y)
plot(x,5*y)

a) 1
b) 2
c) 3
d) 4
e) 5

38
Dr. Brett Freidkes University of South Florida

Answers: Multiple Choice

1) Which of the following is equivalent to 1:0.5:2?

a) linspace(1,0.5,2)
b) linspace(1,3,2)
c) linspace(1,2,2)
d) linspace(1,2,3)
e) linspace(1,2,0.5)

The command 1:0.5:2 will create a list that starts with 1, increments by 0.5, and
ends at 2. So the list is [1 1.5 2].

We have a list that starts at 1, ends at 2, and is 3 elements. Based on the format of
linspace (Figure 12), our answer is linspace(1,2,3). So, answer choice D.

2) The plot below corresponds with which command?

a) plot([1 2], [5 6])


b) plot([1 5], [2 6])
c) plot([1 2], [2 3])
d) plot([2 6], [1 5])
e) plot([2 5], [1 6])

The points that make up this plot are (1,2) and (5,6). Since the x-values are
combined in a vector and the y-values are combined in a separate vector, the
answer ends up being choice B.

39
Dr. Brett Freidkes University of South Florida

3) What color would the plot be if the following code was used?

co = [0 1 0];
plot(x,y,'color',co)

a) Black
b) Green
c) Red
d) White
e) Blue

The 3-element matrix corresponds with the colors red, green, and blue in that
order. Since the red and blue indices are 0 and the green is at a maximum of 1, the
graph will be green. Answer choice B.

4) How many data sets will be shown in the plot created from the code below?

x = 0:0.01:5;
y = x.^3+1;
plot(x,y)
plot(x,2*y)
hold on
plot(x,3*y)
hold off
plot(x,4*y)
plot(x,5*y)

a) 1
b) 2
c) 3
d) 4
e) 5

The first plot is created and immediately overwritten since hold wasn’t on. After
the 2nd plot, we hold the 3rd plot, so we currently have two data sheets on the same
figure. We turn hold off and plot the 4th function and then immediately overwrite it
with the 5th function. So at the end of the day, only 1 function is shown.

40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy