Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

PLOTTING

Programming with Matlab


CALENDAR

Unit What
1 Introduction to MATLAB
2 Flow control & Data Structures
3 Plotting
4 Strings & File IO
5 Complex Numbers
6 Combinatorics
7 Linear Algebra
8 Statistics & Data Analysis
9 Polynomial Approximation,
Curve Fitting
10 Root Finding, Numerical
Differentiation
11 Numerical Integration
12 MATLAB GUI

2
REVIEW OF BASIC 2D PLOTS

• The first lecture gave a brief introduction to basic 2D plotting:

x = linspace(0, 2*pi, 1000);


y = sin(x);
plot(x,y)

• The plot is lacking in terms of presentation


• No axis labels.
• No title.
• Graph cuts off after 2π.
• Number labels are inappropriately small.

• The goals of this lecture are:


• To cover the wide array of plotting functions useful for sciences and
engineering.
• To show how to properly format plots and how to automate the task of
formatting.

3
WHAT IS A HANDLE?

Handle = the part by which a thing is held, carried, or controlled.

• In MATLAB, a Handle is a Data Type, used to “Address”, or “Reference” an object. We can


think of it as a fishing Rod, that allows us to “catch” and “Control” the given object

4
QUIZ

• Let’s define a function f in two different ways:


>> x=1:1:10
>> f1 = @(x) x.^2; % This is a Handle
>> f2 = x.^2; % This is a vector
>> x=1:1000:10000
>> figure, plot (x,f2)
>> figure, plot (x,f1(x)) 1

Which of the two curves belong


to which definition?

A. Fig 2 belongs to both


B. Fig 1 belongs to both
C. Fig 1 Handle, Fig 2 Vector 2
D. Fig 1 Vector, Fig 2 Handle

5
SOLUTION

• Let’s define a function f in two different ways:


>> x = 1:1:10;
>> f1 = @(x) x.^2; % This is an Handle
>> f2 = x.^2; % This is a vector

• Here is the MATLAB memory :

• If we want to plot f2, we simply plot x on one axis, and f2 on the other. There is no way to
calculate f2(100) as x stops at 10.
• If we want to plot f1, we will need to fish the function out of the MATLAB database. We use
the function handle for that. Than we can recalculate it again for any value of x.

6
SOLUTION
• Let’s define a function f in two different ways:
>> x=1:1:10
>> f1 = @(x) x.^2; % This is an Handle
>> f2 = x.^2; % This is a vector
>> x=1:1000:10000 % Redefinition of x
>> figure, plot (x,f2) % We just plot existing x and f
>> figure, plot (x,f1(x)) % We fish f1 out of dbase through
% its handle, and we recalculate it

Check Y axis: figure 1 is wrong as being f1 a vector its values were not recalculated

7
QUIZ (REPRISE)

• Let’s define a function f in two different ways:


>> x=1:1:10
>> f1 = @(x) x.^2; % This is a Handle
>> f2 = x.^2; % This is a vector
>> x=1:1000:10000
>> figure, plot (x,f2)
>> figure, plot (x,f1(x)) 1

Which of the two curves belong


to which definition?

A. Fig 2 belongs to both


B. Fig 1 belongs to both
C. Fig 1 Handle, Fig 2 Vector 2
D. Fig 1 Vector, Fig 2 Handle

8
OVERVIEW OF THE PROPERTY EDITOR

• In our current figure, we can open the property


editor by going to View  Property Editor.
• Here, we can manually select each object
in our plot and modify their properties in the
“More Properties” window.

• In the example on the right, we


currently have the axes object selected.
• The bottom window lists all the
properties of this axes object; each one
can be modified by the user.

• When trying to make consistent plots, it can be


very tedious to have to open the Property Editor
and make manual modifications.
• Fortunately, any desired changes can be done
through code, which allows precise control and
automation.

9
OBJECT PROPERTIES

• We already discussed that we don’t want to use GUIs: error prone, complicated,
and bad for documentation.

WE WANT TO USE SCRITPS

• How do we access to the property editor menu from a script?

We fish it out with a Handle

10
OBJECT HANDLES

• Every plot will always be composed of the following objects:


• Figure object – the window in which the plot is displayed.
• Axes object – the axes and area in which the plot can appear.
• In our current example, we also have a line object.

• Each of these objects can be identified by their handles.


• The handles of the current figure and axes can always be obtained by the commands
gcf and gca, respectively.
• If we are working with multiple plots, we can easily store these handles in variables as
we create the plots, e.g. hFigure1 = gcf.
• To obtain of handle of the object being plotted (in our example, a line), we simply
provide an output to the plotting function, e.g. h = plot(x,y).

• Now that we can identify all the objects in our plot we can easily modify their properties
without having to manually work with the Property Editor.

11
OBJECT PROPERTIES

• We can fetch any property of a graphics object using the get command:
• get(h) – returns all properties of the object identified by handle h.
• get(h, 'PropertyName') – returns the value of property
'PropertyName' of the object identified by handle h.

• We can modify any property using the set command:


• set(h, 'PropertyName', PropertyValue, ...) – sets the values of
'PropertyName' to the specified PropertyValue.
• We can specify any number of properties, i.e.
set(h, 'PName1', PValue1, 'PName2', PValue2, ...).

• For a complete list of properties for each object, either:


• Go to View  Property Editor in your figure.
• Check the MATLAB documentation by searching “<Object Name> properties”,
e.g. “axes properties”.
• The examples that follow will look at some of properties that usually need to be
modified in order to create presentable plots.

12
AXES LIMITS

• MATLAB automatically determines the range of the axes when a plot is created,
but the result is not always suitable.
• In our example, the curve is cut off at 2π but the x-axis (abscissa) ends at 7.
• We would like to modify the right limit of the x-axis to 2π while preserving the left
limit. We would also like more room at the top and bottom of the plot

x = linspace(0, 2*pi, 1000);


y = sin(x);
plot(x,y);

xlimits = get(gca, 'XLim');


set(gca, 'XLim', [xlimits(1), 2*pi])
set(gca, 'YLim', [-1.2, 1.2])

• We use the get command to fetch the x-axis limits since we want to keep the left
limit determined automatically by MATLAB.
• The new x-axis range is [0, 2π] and the new y-axis range is [-1.2, 1.2].

13
AXES TICKS

• Another issue we had with the plot was the size of the number labels on the axes.
• A quick look at the properties list of the axes object shows several font-related
properties: FontName, FontSize, FontAngle, etc.

set(gca, 'FontSize', 25)

• Although this change makes the plot more


viewable, the automatically-chosen x-axis
tick labels remain irrelevant.
• Since this is a sine curve, we may instead
chose to label it in degrees at certain key points.

set(gca, 'XTick', 0:pi/2:2*pi)


set(gca, 'XTickLabel', 0:90:360)
set(gca, 'FontSize', 25)

• XTick specifies the position (remember, we


defined our x-axis vector in radians from 0 to 2π)
of each label XTickLabel.

14
AXES TICKS WITH STRINGS

• Suppose we want to label the x-axis in radians using the “π” character.
• A simple way to accomplish this is by using the “\” symbol, which maps English letters to
Greek letters.
• Using this symbol, the characters “pi” corresponds to the character “π”
• This time, we must specify XTickLabel using a cell array of strings.

set(gca, 'XTick', 0:pi/2:2*pi)


set(gca, 'XTickLabel', {'0', '\pi/2', '\pi', '3\pi/2', '2\pi'})
set(gca, 'FontSize', 25)

• Another method uses a LaTeX interpreter to


format the axes.
• This method has been automated in a
publicly-available MATLAB function
format_ticks.m, which is available on the
MathWorks website.

15
BUILT-IN AXIS MODES

• MATLAB includes various commands to conveniently format axis scaling:


• axis tight – sets the axis limits to the range of the data.
• axis equal – scales all axes equally.
• axis image – a combination of axis tight and axis equal.
• Can be used to format axes without specifying a precise range for your data.

• Other built-in axis modes include:


• axis ij – places the origin of the coordinate system in the upper left corner.
• axis xy – places the origin in the lower left corner (default).
• axis off, axis on – toggle axis lines, tick marks, and labels.

16
LINE SPECIFICATION

• The line object create by the plot function can also be modified using the same
methods; for example, let’s make it a thick, green, dash-dot line.
• First, obtain a handle for the line object by giving an output to the plot command:

h = plot(x,y);
set(h, 'LineStyle', '-.', ...
'LineWidth', 7.0, ...
'Color', 'g')

• A more brief way to accomplish this would


be to specify these attributes from the plot
command directly:

plot(x,y, 'LineStyle', '-.', ...


'LineWidth', 7.0, 'Color', 'g')

• Or, even simpler:

plot(x,y, '-.g', 'LineWidth', 7.0)

17
MULTIPLE PLOTS

• Whenever a plotting function is called (e.g. plot), a figure object is automatically


created for the graph.
• Any subsequent call to a plotting function will overwrite the current figure with a
new graph.
• In the case where multiple plots need to be generated, a new figure object needs
created before each call to a plotting function:

x = -10:0.1:10;
y1 = x.^2 - 8;
y2 = exp(x);
figure, plot(x,y1)
figure, plot(x,y2)

• A new figure window with default properties is created simply by calling figure.
• Be careful when formatting figure objects using the gcf handle, as it refers to the
most recently created figure object.

18
SUBPLOTS

• Suppose we want to have multiple plots on one figure.


• The function subplot(m,n,p) divides the figure window into an m-by-n grid and
creates an axis in the pth location:

subplot(2,2,1)
text(.3,.5, 'Subplot #1')
subplot(2,2,2)
text(.3,.5, 'Subplot #2')
subplot(2,2,3)
text(.3,.5, 'Subplot #3')
subplot(2,2,4)
text(.3,.5, 'Subplot #4')

19
SUBPLOTS

• If we want to have a plot that covers multiple subplot positions, we can make the
input p a vector that specifies these positions.

x = -5:0.1:5;
y1 = exp(x);
y2 = sqrt(abs(x));
y3 = sin(x)./x;
subplot(2,2,[1 3]), plot(x,y1)
subplot(2,2,2), plot(x,y2)
subplot(2,2,4), plot(x,y3)

• In this example, we wanted the plot


of y1 to occupy subplot positions 1
and 3, so p = [1 3].
• Note that the occupied positions include all those spanned by p as well; hence,
setting p = [1 4] would occupy all 4 subplot positions (i.e. just a standard plot).

20
OVERLAID PLOTS

• Suppose we want to have multiple curves on a single graph.


• After the figure object is create from the first call to the plotting function, the hold
function can be used to retain the current graph, while other graphs are added:

x = linspace(0, 2*pi, 1000);


f = sin(x);
g = 0.6*cos(0.5*x);
plot(x, f, '-b', 'LineWidth', 3)
hold on
plot(x, g, '--r', 'LineWidth', 3)
hold off

• The command hold on retains the current figure as new graphs are added.
• hold off reverts this behavior; any subsequent calls to a plotting function will
overwrite the figure.
• Any of the graph’s properties can be modified as previously shown regardless of
the hold function; the previous formatting was applied to obtain the plot shown.

21
TITLES, AXIS LABELS, AND LEGENDS

• Titles, x-axis and y-axis labels, and legends can be easily added with their
respective commands: title, xlabel, ylabel, and legend.

xlabel('x', 'FontName', 'Arial')


ylabel('f(x); g(x)', 'FontName', 'Arial')
hLegend = legend('f(x) = sin(x)', 'g(x) = 0.6*cos(0.5*x)');
set(hLegend, 'FontName', 'Arial', 'FontSize', 18)
title('Example Plot', 'FontName', 'Arial')

• These functions only require a single input argument: a string of the label’s
contents.
• The remaining arguments can be 'PropertyName', PropertyValue, ... as
we’ve seen throughout this lecture to modify properties such as font size.

22
FIGURE SIZE

• Although it is possible to resize figures after saving them in image format,


changing the aspect ratio has negative consequences on overall appearance.

• Furthermore, if multiple plots need to be presented in a report, rescaling the figure


manually by dragging it by the corner is imprecise and will lead to differently-sized
graphs.

• Fortunately, we can modify the properties of our figure object to obtain the desired
results; there are three relevant properties:
• PaperPosition – a 4 element vector [left, bottom, width,
height] describing position and size of the figure in the context of a printed
page.
• PaperPositionMode – Allows two settings:
• manual uses the values specified by PaperPosition;
• auto uses the same size as it appears on the computer screen.
• PaperUnits – Units that define the PaperPosition property (inches by
default).

23
FIGURE SIZE

• Suppose we want our plot to appear wider when we save it as an image.

figSize = get(gcf, 'PaperPosition');


set(gcf, 'PaperPosition', [figSize(1:2), ...
figSize(3)+3, figSize(4)])
set(gcf, 'PaperPositionMode', 'manual')

• The first line of code above returns a 4 element array figSize = [left,
bottom, width, height].
• left and bottom define the distance from the lower-left corner of the page to the
lower-left corner of the figure window; these are irrelevant here.
• In our example, we only want to change the width of the plot to make it wider.
• We add 3 inches to the current width and keep all other properties the same.

24
FILE FORMATS

• Figures can be saved in several formats; some of the more useful formats are:
• .fig – MATLAB figure file; useful for preserving all plot information, especially in
the case of future work.
• .bmp – Uncompressed image file.
• .jpeg – Compressed image file.
• .eps – Object-oriented image file; Scalable format.

• The most ideal format to save your plots for the purpose of presentation is .eps.
• Since it is object-oriented, rather than pixel-based, it is very tolerant to rescaling.
• Figures can be saved via code using either saveas or print functions:

print(gcf, 'ExamplePlot', '-depsc')


saveas(gcf, 'ExamplePlot.eps', 'epsc')

25
GRAPH PRESENTATION

BAD BETTER

26
OTHER PLOTS & VISUALIZATIONS

• Thus far, we have only used 2-D line plots to demonstrate proper formatting.
• MATLAB has a wide variety of specialized plotting functions:
• plot3 – 3-D line plot.
• semilogx, semilogy, loglog – logarithmic plots.
• imagesc – visualize a matrix as an image.
• bar, hist – bar plots and histograms.
• mesh, surf – 3-D surface and mesh plots.
• polar – plot function in polar coordinates on a Cartesian plane.
• quiver – plot velocity vectors as arrows.
• stem – plot discrete data values as stems that extend from the x-axis.
• scatter – scatter plot.
• stairs – stairstep plot for piecewise constant functions.

• All of the concepts that we’ve previously learned can and should be applied to any
of these and all other types of plots.

27
QUIZ

• We want to draw the function Z = F(x,y) = x+y with x and y = [−2,−1,0,1,2]


• Is the following a valid MATLAB code ?

>> X= -2:1:2
>> Y= -2:1:2 Z=X+Y
>> Z= X+Y
x,y −2 −1 0 1 2
A. No −2 −4 −3 −2 −1 0
B. Yes −1 −3 −2 −1 0 1
C. Yes, but does not do what we want! 0 −2 −1 0 1 2
1 −1 0 1 2 3
2 0 1 2 3 4

28
QUIZ

• We want to draw the function Z = F(x,y) = x+y with x and y = [−2, −1,0,1,2]
• Is the following a valid MATLAB code ?

>> X= -2:1:2
>> Y= -2:1:2
>> Z= X+Y
x,y −2 −1 0 1 2
A. No −2 −4 −3 −2 −1 0
B. Yes
−1 −3 −2 −1 0 1
C. Yes, but does not do what we want!:
0 −2 −1 0 1 2
Z = [−4 −2 0 2 4]
1 −1 0 1 2 3
We wanted a 2-dimensional function (matrix), 2 0 1 2 3 4
but we got a vector

29
2D FUNCTIONS

• If X and Y are vectors, the result of X+Y will be a vector whose entries are sums of
the corresponding values in X and Y
• If we want to obtain a matrix Z=X+X, we need to give MATLAB matrices X and Y as
input!
[X,Y] = meshgrid(-2:1:2);
Z = X + Y;

x −2 −1 0 1 2 y x,y −2 −1 0 1 2
−2 −1 0 1 2 −2 −2 −2 −2 −2 −2 −2 −4 −3 −2 −1 0
−2 −1 0 1 2 −1 −1 −1 −1 −1 −1 −1 −3 −2 −1 0 1
−2 −1 0 1 2
+ 0 0 0 0 0 0
= 0 −2 −1 0 1 2
−2 −1 0 1 2 1 1 1 1 1 1 1 −1 0 1 2 3
−2 −1 0 1 2 2 1 1 1 1 1 2 0 1 2 3 4

30
PLOTTING 3D SURFACES

• A function of two variables (2D function) can be plotted as a surface in 3D


• To plot a surface, we need to know its height z at each point (x,y), i.e., z = f(x,y).
• The meshgrid function can be used to return the x and y coordinates of each
point in our domain in separate matrices.

2 +𝑦 2 )
• For example, plot the Gaussian function, 𝑓 ሺ𝑥, 𝑦ሻ = 𝑒 −(𝑥 .

[X,Y] = meshgrid(-2:0.1:2);
Z = exp(-X.^2 - Y.^2);

• The x and y coordinates of all points (x,y) of our domain are stored separately in
matrices X and Y, respectively.
• Using vector operations, we can calculate the height of our function at all points
(x,y) simulatenously and store the result in Z.

31
PLOTTING 3D SURFACES
Source www.mathworks.com

• This result can be visualized as a colored


wireframe mesh, with color proportional to
surface height Z.

mesh(X,Y,Z)

• We can also visualize it as a shaded


surface.

figure
surf(X,Y,Z, ...
'FaceColor', 'interp', ...
'EdgeColor', 'none', ...
'FaceLighting', 'phong')
daspect([2 2 1])
axis tight
view(-50,30)
camlight left

32
PLOTTING 3D SURFACES

• Several useful functions were used to format the surface plot.

• daspect([aspect_ratio]) specifies the relative scaling between the three


axes, e.g., daspect([1 1 3]) means 1 unit in x = 1 unit in y = 3 units in z.

• view(az, el) changes the viewpoint


in terms of azimuth (az) and elevation (el).

• camlight(az,el) creates a light at specified


azimuth and elevation with respect to the [1]
current camera position.
camlight headlight or camlight(0,0) camlight right

Source www.mathworks.com

33
BAR PLOTS

• bar(x,Y) draws bars for each column in Y at locations specified in x.


• For example, we want to plot the medal counts for the top 5 countries in the 2012
Olympics, with the countries on the bottom axis.
• Organize data as follows: Medal = [USA CHN GBR RUS KOR].

G = [46 38 29 24 13];
S = [29 27 17 26 8];
B = [29 23 19 32 7];

%Create vertical bar chart


h = bar(1:5, [G' S' B']);
title(['Medal count for ' ...
'top five countries ' ...
'in 2012 Olympics'])
ylabel('Number of medals')
xlabel('Country')
legend('Gold', 'Silver', 'Bronze')

Source www.mathworks.com

34
BAR PLOTS

• This plot contains three bar objects, one for each set of medal data, G, S, and B.
• Thus, when we stored the handle h = bar(... we obtained a vector h, where h(1),
h(2), and h(3) identifies each respective bar object, G, S, and B.

%Change the face color the bars to match the medals (Red, green,
Blue)
set(h(1), 'FaceColor', [0.8 0.8 0])
set(h(2), 'FaceColor', [0.5 0.5 0.5])
set(h(3), 'FaceColor', [0.55 0.41 0.21])

%Change the x-axis labels


%to names instead of numbers
set(gca, 'XTickLabel', ...
{'USA', 'CHN', ...
'GBR', 'RUS', 'KOR'})

Source www.mathworks.com

35
VISUALIZE DATA AS AN IMAGE

• imagesc(A) displays matrix A as an image where each element of A corresponds


to a rectangular area in the image.
• The value of each element determines the color of the corresponding patch.
0.5 14
x = [1:10; 3:12; 5:14]; 12
1
imagesc(x) 10
1.5
colorbar 8
2
• The default colormap is jet. 6
2.5
4
3
• Other built in colormaps are available: 2
3.5
2 4 6 8 10
0.5 0.5 0.5
1 1 1
1.5 1.5 1.5
2 2 2
2.5 2.5 2.5
3 3 3
3.5 3.5 3.5
2 4 6 8 10 2 4 6 8 10 2 4 6 8 10

colormap(hot) colormap(gray) colormap(cool)

36
QUIZ

• A colormap is simply a 256x3 matrix that specifies 256 different RGB values from 0
to 1 to which elements of a matrix are mapped. The 1 st column represents red, the
2nd green, and the 3rd blue.

• QUIZ 1: How do we create a green colormap, starting from the vectors


V=[1:255]/255; Z=zeros(255,1) ;

A. Map=[V’ V’ V’]

B. Map=[V’ Z’ Z’]; 0.5

C. Map=[Z’ V’ Z’]; 1.5

D. Map=[Z’ Z’ V’]; 2.5

E. Map=[Z’ Z’ Z’];
3.5
1 2 3 4 5 6 7 8 9 10

37
QUIZ

• A colormap is simply a 256x3 matrix that specifies 256 different RGB values from 0
to 1 to which elements of a matrix are mapped. The 1 st column represents red, the
2nd green, and the 3rd blue.

• QUIZ 2: How do we create a gray colormap, starting from the vectors


V=[1:255]/255 ; Z=zeros(1,255) ?

A. Map=[V' V' V'];


0.5

B. Map=[V' Z' Z']; 1


1.5

C. Map=[Z' V' Z']; 2


2.5

D. Map=[Z' V' Z']; 3


3.5
2 4 6 8 10
E. Map=[Z' Z' Z'];

38
VISUALIZE DATA AS AN IMAGE

• A colormap is simply a 256x3 matrix that specifies 256 different RGB values to
which elements of a matrix are mapped. T
0 1 254 255
• For example, colormap(gray) would look like:
0 1 … 254 255
• The first rows [0,0,0], [1,1,1], etc. represent
dark colors and are mapped to small values. 0 1 254 255
• The later rows represent bright colors and
are mapped to large values. T
0 0 0 0
• Let’s create a custom green colormap:
0 1 … 254 255
• The 1st column represents red, the
2nd green, and the 3rd blue. 0 0 0 0

x = [1:10; 3:12; 5:14]; 0.5

imagesc(x) 1

1.5

map = zeros(256,3); 2

map(:,2) = (0:255)/255; 2.5

3
colormap(map) 3.5
1 2 3 4 5 6 7 8 9 10

39
STEM AND PIECEWISE PLOTS

• stairs(x,y) draws a stairstep graph of the elements in y at for each


corresponding location specified in x.

• stem(x,y) plots the data y as a stem that extends to the x-axis. The values of y
are indicated by circles that terminate each stem.

• If x is not specified for either function, then x = 1:length(y).

figure
x = linspace(0, 4*pi, 40);
y = sin(x);
stairs(y)

figure
stem(y)

40

You might also like