Sunteți pe pagina 1din 28

12/17/2010 Plotting in Matlab

Advanced Matlab
Open Blog with: Engineering Solutions, Algorithms, Advanced Source Code and Science related
contents

RSS Feed Comments

FusionCharts.com Ads by Google

Ads by Google 3D Visualization MATLAB 3D Graph 2D Modeling

Home
Submit
Infos
Writing Post (Tutorial)

Search

Plotting in Matlab
June 1, 2010 by Admin
Filed under: Graphics, Utility
6 Comments
Rating: +6 (from 6 votes)

Rating: 9.9/10 (10 votes cast)

Adrian Bowyer -The Future


On Innovation,unemployment, Economy
Ericsson.com - 2020 Shaping Ideas
youtube.com/ericssonmultimedia
Ads by Google

by Matt Dunham

Matlab has excellent support for data visualization and graphics with over 70 types of plots currently
available. We won’t be able to go into all of them here, nor will we need to, as they all operate in
advancedmcode.org/plotting-in-matlab.… 1/28
12/17/2010 Plotting in Matlab
very similar ways. In fact, by understanding how Matlab plotting works in general, we’ll be able to
see most plot types as simple variations of each other. Fundamentally, they all use the same basic
constructs.

Contents
Useful Functions
Plotting 2D Data
Plotting 2D Functions
Handles and Customization
3D Surface and Contour Plots
Interpolation
Annotations and the Plot Editor
Latex
Coordinate Conversion
Multiple Axes Per Figure
Other Types of Plots
Root Properties
Saving and Printing
Rotating Figures and Creating Movies
User Input & Callbacks
Custom Functions

Useful Functions
figure, clf, close, hold, axes, gcf, gca, set, get
axis, grid, title, xlabel, ylabel, zlabel, legend, box, annotation
shading, material, camlight, alpha, view, colormap, colorbar, linespec
plot, plot3, surf, surfc, contour, contourf, mesh, bar, bar3, pie3,
loglog, semilogx, semilogy, hist, histc
fplot, ezplot, ezsurf, ezcontour, ezmesh
meshgrid, griddata, peaks,
copyobj, allchild, findobj, findall, ancestor, ishandle
camorbit, pause, camdolly, campan, camzoom, camroll, avifile, movie
subplot, print, ginput, gtext, placeFigures

Plotting 2D Data
The best way to learn how to plot is to see many examples so we’ll jump right in and plot some data
using the plot() command.
rand('twister',0); % seed the random number generator
X = 5*rand(100,1); y = rand*X + rand(100,1); % generate some synthetic data
f1 = figure; % create a blank figure
p1 = plot(X,y,'.'); % plot X vs y

advancedmcode.org/plotting-in-matlab.… 2/28
12/17/2010 Plotting in Matlab

We have told Matlab to plot the data in X vs the data in y and to display a blue solid dot for each data
point. There are many different types of marker and line styles available. For a complete list type doc
linespec. Lets make a few changes. Recall that we can break long statements into multiple lines
using ellipses, …
clf(f1); % clear the figure
p2 = plot(X,y,'o','MarkerEdgeColor','k',... % plot larger red circles with black edges
'MarkerFaceColor','r',...
'MarkerSize',8);
axis([-1,6,-1,5]); % set the axis limits

advancedmcode.org/plotting-in-matlab.… 3/28
12/17/2010 Plotting in Matlab

Plotting 2D Functions
Plotting functions is very similar to the data plotting we just performed. We begin by creating two
functions, (see the section on function handles) and a grid of points, the domain. We then evaluate
each function at every point along this domain and plot the resulting x,y pairs, connecting
consecutive dots. Here we plot both functions on the same set of axes.
f = @(x) x.^2; % create a function of x, namely f(x) = x.^2
g = @(x) 5*sin(x)+5; % create a second function of x, g(x) = 5*sin(x) + 5
res = 0.001; % resolution of the plot
domain = -pi:res:pi; % the domain of x, (i.e. points at which to evaluate f,g)
f2 = figure; % open a new figure
p3 = plot(domain,f(domain)); % plot f, w.r.t. x over its domain
hold on; % tell Matlab to add future plots to the same set of axes
p4 = plot(domain,g(domain)); % plot the second function.

Not bad for a first attempt but there are a lot of improvements we could make. Lets try again but this
time, we will plot each function in its own color, change the line widths and types, the tick marks, the
range of the axes, the background color, the font size, and add labels, a title, and a legend. We’ll
keep the functions and domain the same. Let us also add error bars to one of the functions denoting
one standard deviation of the dependent variable.
f3 = figure('Color',[1,1,1]); hold on; % new figure with a white background
p5 = plot(domain,f(domain),'--r','LineWidth',3); % plot a thick dashed red line
p6 = plot(domain,g(domain),'-b','LineWidth',3); % plot a thick solid blue line
subdomain = domain(1:400:end); % we will plot error bars at every 400th point
oneSTD = std(g(domain)); % standard deviation of g(domain)
oneSTD = oneSTD*ones(size(subdomain)); % make correct size, as needed by errorbar
p7 = errorbar(subdomain,g(subdomain),oneSTD); % plot the error bars
title('example figure','FontSize',12); % add a title
xlabel('distance','FontSize',12); % label the horizontal axis
ylabel('height','FontSize',12); % label the vertical axis
axis([-3,3,-5,15]); % set the axis range

advancedmcode.org/plotting-in-matlab.… 4/28
12/17/2010 Plotting in Matlab
grid on; % add grid lines

Handles and Customization


Figure generation in Matlab is object oriented. Figures are top level objects and contain other objects
such as axes and annotations. Axes further contain sub-objects such as plots and labels, which are
often built up from smaller objects too. All of these objects have attributes that can be retrieved and,
(for the most part) changed, using the get() and set() commands. The first parameter to these
functions is a handle to an object. We can obtain such handles when we create the objects as in fig =
figure.

After the fact, we can obtain the handle to the current figure by using the gcf() command or to the
current set of axes by using the gca() command. We can also obtain handles to other types of objects
using the findobj(), findall() , ancestor() ,and allchild() functions, but since this is very rarely
necessary, we will not go into it here. Read their help entries if you are interested. We can see a list
of all of the attributes of an object by typing get(handle) at the command prompt. The command
set(handle) lists not only the attributes but also valid potential values.

We can test if a variable is a valid handle or not with the ishandle() method. Figure handles are
actually just integer values starting at 1 that have been registered with the root graphics object.

Below, we use the set() method to change a number of axes attributes. Multiple attributes can be
changed in one command, (or in multiple commands if you prefer) and the name of the attribute
always precedes its new value.
set(gca,'box' ,'on' ... % draw a box around the figure
,'LineWidth', 2 ... % increase the line width
,'FontSize' ,12 ... % increase the font size

advancedmcode.org/plotting-in-matlab.… 5/28
12/17/2010 Plotting in Matlab
,'XTick' ,[-3,0,3]... % only these x-ticks
,'YTick' ,[0,5,10]); % only these y-ticks
Xequal = domain(abs(f(domain) - g(domain)) < 2*res); % find where the two graphs meet
p8 = plot(Xequal,f(Xequal),'o','MarkerFaceColor','g'... % plot green circles there
,'MarkerEdgeColor','k'... % black border around circles
,'LineWidth' , 2 ... % thicken black border
,'MarkerSize' ,10); % increase the circle size
legend([p5,p6,p8],{'f(x) = x^2','g(x) = 5*sin(x)+5','f(x) == g(x)'},'Location','NorthWest');
% Prevent close commands from closing this figure. We will use it again later.
set(f3,'HandleVisibility','off');

As you can see, most plotting commands, such as legend() above, have many possible parameters
and parameterizations. It would be redundant to go into them all here; type doc legend ,for
example, to see more information on the legend command.

There are Matlab functions designed to make function plotting easier such as fplot() , ezplot() ,
ezsurf() , ezmesh() , ezcontour() , etc… While these can be useful for quick and dirty figures, they can
make customization more difficult and so we recommend using, and learning to use, plot() instead.
All of these functions take function handles as arguements and the ez*** functions auto set the axes
limits for you.

The loglog() , semilogx() , and semilogy() functions are useful for plotting on logarithmic scales.
However we can achieve the exact same effect by plotting with plot() and calling
set(gca,’XScale’,'log’) and/or set(gca,’YScale’,'log’) . We can reverse the direction of an axis
with set(gca,’YDir’,'reverse’) or set(gca,’XDir’,'reverse’) and move an axis with
set(gca,’YAxisLocation’,'right’) or set(gca,’XAxisLocation’,'top’) . Recall that we can find the
names of these properties with get(gca) or the valid values with say set(gca,’YDir’) .

Many plotting functions, plot() in particular, but also line() and scatter() ,allow you draw multiple
curves, lines or batches of data with a single command. See their help entries for more information.
advancedmcode.org/plotting-in-matlab.… 6/28
12/17/2010 Plotting in Matlab
We will now examine a number of other types of plots before discussing more advanced plotting
options, such as adding multiple axes per figure to display graphs side by side, or the inclusion of
various annotations such as arrows, and text. We have already seen how to change basic properties
such as line widths and color. Doing so can considerably improve the look of figures, especially when
they will appear in external documents.

3D Surface and Contour Plots


To graph a function of two variables we need to first evaluate that function over a grid of points, not
just a line as in the 2D case. We use the meshgrid() function to create such a grid. There are several
3d plot types available. Here we use surf(), which plots the surface of the function, contourf() , which
plots the contour lines of a function and fills the area between them with color, and mesh() , which is
similar to surf(), displaying a wire mesh rather than a solid surface. The colors used in each are
specified by the current colormap and can be changed by using the colormap() command. Type doc
colormap for a list of options. There are several other 3d plotting functions: plot3() for instance is
the 3d generalization of plot().
f = @(x,y) exp(cos(sqrt(x.^2 + y.^2))); % a function of two variables
d = -2*pi:0.1:2*pi; % domain for both x,y
[X,Y] = meshgrid(d,d); % create a grid of points
Z = f(X,Y); % evaluate f at every point on grid

Some functions, while still vectorized, will only operate on vectors and not matrices. The mvnpdf()
function for example interprets a matrix of inputs, (say n-by-d), as n, d-dimensional inputs, not n*d
1-by-1 inputs. We can still plot such functions in 3D with a few small changes. After obtaining X and
Y from meshgrid(), save X’s size, evaluate f by passing in X and Y as column vectors, (using the :
operator), and then reshape the output Z back to the original size and continue as before.
[nrows,ncols] = size(X); % first obtain the size of X
Z1 = f(X(:),Y(:)); % convert X,Y to column vectors and evaluate f
Z1 = reshape(Z1,nrows,ncols); % reshape

Here are some more example plots.


f4 = figure; % create a new figure
p9 = surf(X,Y,Z); % plot the surface of the function
shading interp; % interpolate between the points
material dull; % alter the reflectance
camlight(90,0); % add some light - see doc camlight
alpha(0.8); % make slightly transparent
box on; % same as set(gca,'box','on')

advancedmcode.org/plotting-in-matlab.… 7/28
12/17/2010 Plotting in Matlab

f5 = figure; % create a new figure


p10 = contourf(X,Y,Z); % contour plot
colorbar; % add a colorbar
set(gca,'XTick',[],'YTick',[]); % remove all ticks

f6 = figure; % create a new figure


r = 1:3:126; % mesh plots look better at lower resolution
p11 = mesh(X(r,r),Y(r,r),Z(r,r)); % plot a mesh grid
view([-15 60]); % change the viewing angle - see doc view
colormap Copper; % change the colormap
axis off; % turn off the axis completely

advancedmcode.org/plotting-in-matlab.… 8/28
12/17/2010 Plotting in Matlab

Note, the command view([90,90]) can be very useful to rotate a plot by 90 degrees, effectively
reversing the locations of the x and y axes.

Below we display a 3d bar plot of the same underlying data. We take advantage of the mat2cell()
command to partition the Z data into 21×21 6-by-6 blocks, each block stored within a cell. We then
use the cellfun() function to replace each block with its mean. We can use this same technique to
apply any function to arbitrary sized blocks of a matrix. Note that when the size of the data within
cells is different, ‘UniformOutput’ must be set to false.
f7 = figure;
grouped = mat2cell(Z,6*ones(21,1),6*ones(21,1)); % partition matrix into 6-by-6 blocks
fconv = @(X)mean(X(:)); % create function handle
convCell=cellfun(fconv,grouped,...
'UniformOutput',false); % apply that function to every block
convMat = cell2mat(convCell); % convert back to a, (smaller) matrix
p12 = bar3(convMat); % display a 3d bar plot of the aggregated data
colormap jet % change the color map

advancedmcode.org/plotting-in-matlab.… 9/28
12/17/2010 Plotting in Matlab

Virtually everything we said about customizing 2D plots applies equally to 3D plots. We can add a
title, a legend, labels using xlabel() , ylabel() , and zlabel() , change the range of the axes, the font
size, etc.

Interpolation
3D plotting in Matlab requires a uniform grid of points but the data we obtain from experiments or
measurements may not satisfy this constraint. In such cases, we can use the griddata() function to
interpolate along a uniform grid of points for us.
f8 = figure;
randn('state',0); % seed the normal random num generator
X = randn(100,50); % data captured at these points.
Y = randn(100,50);
Z = cos(X.^2).*exp(X.^2 - Y.^2); % value of data at these points
d = -1:0.1:1; % X,Y range of our data
[XI, YI] = meshgrid(d,d); % create our grid as before
ZI = griddata(X,Y,Z,XI,YI); % interpolate to obtain ZI
p13 = mesh(XI,YI,ZI); % mesh of the interpolated points

advancedmcode.org/plotting-in-matlab.… 10/28
12/17/2010 Plotting in Matlab

Annotations and the Plot Editor


Matlab provides an interactive graphical interface for modifying and inspecting existing figures. This
mode can be entered by selecting ‘view->Figure Palette’ or by selecting the appropriate shortcut
button on the figure toolbar. Here we can add annotations such as text, arrows, and shapes as you
would in a program like powerpoint. We can also inspect and change attributes as an alternative to
using set() and get() .

Once you have added elements, you can see the m-code that generates these objects by going to ‘File
-> Generate M-File’. It is usually easier to add annotations graphically first, generate the m-code and
then add the appropriate lines to the original source file so that we can regenerate the complete
figure at will. Alternatively, you can save a Matlab figure as a .fig file maintaining all of the graphics
object information for future editing.

We will now add a few annotations to one of the previous figures. Annotations are placed relative to
the figure window, not the axes. The location is, by default, specified by normalized coordinates
between 0 and 1 so that [0.8 0.4] is the point 80% of the width from the left and 40% of the height
from the bottom. In the case of a line or an arrow, we specify two x-y pairs, denoting the start and
end points. In the case of a text box we specify four numbers, the x and y coordinates followed by
the width and height of the box. Type doc annotation for more information. These commands
were generated automatically after adding the annotations in the plot editor.
figure(f3);
% the text arrow
annotation(f3, 'textarrow' , [0.6616 0.5251],[0.1997 0.3038] ,...
'TextEdgeColor' , 'none' ,...
'TextLineWidth' , 2 ,...
'FontSize' , 12 ,...
'String' , {'global minimum'} ,...
'HeadStyle' , 'deltoid' ,...
'LineStyle' , '--' ,...
'LineWidth' ,2 ,...

advancedmcode.org/plotting-in-matlab.… 11/28
12/17/2010 Plotting in Matlab
'Color' , [0.07843 0.1686 0.549] );
% the dotted line
annotation(f3, 'line' , [0.7176 0.7176],[0.7176 0.4154] ,...
'LineStyle' , '-.' ,...
'LineWidth' ,1 ,...
'Color' , [0 0 1] );
% the text box
annotation(f3, 'textbox' , [0.59 0.47 0.15 0.05] ,...
'String' , {'g(c) - f(c)'} ,...
'FontSize' , 12 ,...
'FitBoxToText' , 'off' ,...
'LineStyle' , 'none' );
set(f3,'HandleVisibility','on');

Latex
Matlab supports the inclusion of both tex and latex markups in figures. This can be useful when you
want to include mathematical formulas. For many purposes, simple tex is sufficient. For example, you
can write super scripts with the ^ character and subscripts with the _ character, (notice the legend)
and include Greek letters using say \alpha or \gamma. To include more complicated latex markups,
you have to specify that you want to use the latex interpreter and then surround the mathematical
text in $ symbols as shown below. Tex and Latex markups are supported in annotations, legends,
and titles but unfortunately not in axis labels via the xlabel() , ylabel() , zlabel() commands or in axis
tick labels. If you want to use latex in these locations, you have to add the text manually via
annotations.
annotation(f3, 'textbox' , [0.2277 0.6333 0.2081 0.0625] ,...
'Interpreter' , 'latex' ,...
'String',{'$M_e = \frac{M_o}{\sqrt{1 - \frac{v^2}{c^2}}}$'},...
'FontSize' , 14 ,...

advancedmcode.org/plotting-in-matlab.… 12/28
12/17/2010 Plotting in Matlab
'FitBoxToText' , 'on' ,...
'LineStyle' , 'none');

Coordinate Conversion
Sometimes we would like to specify where an annotation should go relative to the current set of axes,
rather than relative to the figure window as a whole. For instance, perhaps you would like an arrow
to point at coordinate (3,4) on your current axes; what point is this relative to the whole figure?
Below is some code to perform this conversion. Save it to a file and uncomment the code to create
the function rel2abs() .
function [xabs,yabs] = rel2abs(xpos,ypos)
ax = gca;
xlim = get(ax,'xlim') ; ylim = get(ax,'ylim');
xmin = xlim(1) ; xmax = xlim(2);
ymin = ylim(1) ; ymax = ylim(2);
xscale = xmax - xmin ; yscale = ymax - ymin;
axAbs = get(ax,'Position');
xabs = axAbs(1) + ((xpos-xmin) ./ xscale).*axAbs(3);
yabs = axAbs(2) + ((ypos-ymin) ./ yscale).*axAbs(4);
end

Multiple Axes Per Figure


Sometimes it can be useful to display multiple sets of axes in a single figure, perhaps to connect them
graphically via annotations or just display them next to each other in a compact and convenient way.
If we want the axes evenly spaced in a grid, the subplot() command can be useful but to have more
varied and customizable configurations, we have to add the axes manually. To do so, we take
advantage of the ‘Parent’ attribute of the graphics objects. Recall that figures are composed of axes
advancedmcode.org/plotting-in-matlab.… 13/28
12/17/2010 Plotting in Matlab
and annotation objects and axes are composed of various plot objects. We will create a new plot and
add it along with some of the plots we have already done. The copyobj(h,p) function copies a
graphics object with handle h and assigns the new object to parent p.
f9 = figure; % create new figure
sp = 0.05; % space between axes in %
w = 0.2667; % size of each fig edge
colormap gray; % make them all black & white
for i=4:6
figure(i+1); % open the figure
set(copyobj(gca,f9),'Position' ,... % copy object and set its position
[sp+(i-4)*(w+sp),2*w+3*sp,w,w]);
end
newAx = axes('Parent',f9,'Position',... % create new axes
[2*sp+w,2*sp+w,w,w]);
surfc(peaks,'Parent',newAx); % plot built in function
for i=7:8
figure(i+1); % open figure
set(copyobj(gca,f9),'Position' ,... % copy object and set position.
[sp + (i-7)*(2*w+2*sp),sp,w,w]);
end

Note, we call figure(i+1) here rather than figure(i) because a Matlab document publishing anomaly
offsets the figure handles by one. Normally you would go figure(i).

Recall that the hold command applies to axes objects and not figure objects. Keep this in mind when
debugging problems you might face with multiple axes.

Other Types of Plots


There are many other types of plots supported by Matlab; we briefly show how to create a few of
them here.

advancedmcode.org/plotting-in-matlab.… 14/28
12/17/2010 Plotting in Matlab
Create a 3d pie chart and ‘explode’ the largest piece.
figure;
data = [2 4 9 3 7 2 1 1]; % some hypothetical data
explode = double(data == max(data)); % turn on bit corresponding to largest piece
pie3(data,explode); % create a 3d pie chart
colormap jet; % set the color scheme

Plot the normal distribution and shade the tails using an area() plot. Add a small stem plot using the
stem() command.
figure;
domain = -4:0.01:4;
% We shade two regions with the area command
area(domain(1:fix(end/3)),normpdf(domain(1:fix(end/3)))); hold on;
area(domain(fix(2*end/3):end),normpdf(domain(fix(2*end/3):end)));
plot(domain,normpdf(domain),'-r','LineWidth',3);
stem([-0.7,0.1,0.4],normpdf([-0.7,0.1,0.4]),'LineWidth',2);
axis([-4,4,0,0.5]);
set(gca,'XMinorTick','on'); % Include minor tick marks too
set(gca,'YMinorTick','on');
grid on;

advancedmcode.org/plotting-in-matlab.… 15/28
12/17/2010 Plotting in Matlab

Display a histogram of a hypothetical class grade distribution.


figure;
grades = fix(normrnd(70,10,100,1));
hist(grades); % plot the histogram
xlabel('percent'); ylabel('count');
title('grade distribution');
set(gca,'XLim',[0,100],'YGrid','on');
set(gca,'YMinorTick','on');

Here we organize marks into bins representing letter grades. We use the extremely quick histc()
function to count the number of data points that fall between specified edges. Once we have obtained
the counts, we can visualize them with the bar() function.
advancedmcode.org/plotting-in-matlab.… 16/28
12/17/2010 Plotting in Matlab
figure;
bins = [0,50,55,60,64,68,72,76,80,85,90,inf]; % The bins
letters = {'F','D','C-','C','C+','B-','B','B+','A-','A','A+'}; % The labels
counts = histc(grades,bins); % count grades
bar(counts(1:end-1)); % plot counts
set(gca,'XTickLabel',letters,'Ygrid','on'); % set tick labels
xlabel('grade'); ylabel('count');
title('grade distribution');
set(gca,'YMinorTick','on')

There are many other plot types available. Search help for ‘Figures, Plots, and Graphs’ for a full list.

Root Properties
The top level Matlab graphics object is root and its handle is 0. We can access and set the root
attributes as we would any other graphics handle object using get(0) and set(0). Root’s most useful
attribute is probably ‘ScreenSize’, which gives the current size, (resolution) of the screen in pixels, by
default, or in what ever units the ‘Units’ property has been set to. If you work with multiple
simultaneous monitors, the ‘MonitorPositions’ attribute is also useful. Here we obtain the screen size
and demonstrate how to maximize a figure programatically.
set(0,'Units','pixels'); % set the units to pixels
screenSize = get(0,'ScreenSize') % get the monitor resolution
hgap = 5; vgap = 45;
width = screenSize(3)-2*hgap;
height = screenSize(4)-2*vgap;
newPosition = [hgap,vgap,width,height];
f = figure('Position',newPosition,'ToolBar','none'); % set the size and position
close(f); % close the figure

screenSize =
1 1 1280 1024

advancedmcode.org/plotting-in-matlab.… 17/28
12/17/2010 Plotting in Matlab
As root is the top level graphics object, we can query it for a list of the handles of all of the current
figures using the allchild() function.
handles = allchild(0)'

handles =
Columns 1 through 13
14 13 12 11 9 8 7 6 5 10 4 3 2
Column 14
1

Window size defaults and related settings as well as the maximum recursion limit is also set here; I
suppose for lack of a better place.

Saving and Printing


We can print figures and save them as any major graphics type from the file drop down menu of a
figure window. Also here is the ‘export setup’ option which opens a window where the default figure
resolution and size settings can be set. Newer versions of Matlab also let you automatically increase
the line widths and font sizes of the figures you are exporting. To save or print programatically, we
can use the print() function. Here we save the figure as a jpeg. Type doc print for more details.
figure(f8);
print -djpeg c:\windows\temp\test.jpg % save the current figure as a jpeg

If you find that there is too much white space surrounding the exported figure, (a particular problem
when exporting to pdf) try changing the figure’s paper size before exporting, with the following
commands.
pos = get(gcf,'Position');
set(gcf,'PaperSize',pos(3:4));
set(gcf,'PaperPositionMode','auto');
close(f8);

Rotating Figures and Creating Movies


Figures can be rotated or moved with the mouse by first clicking on the appropriate shortcut button
on a figure window toolbar. However, we can also automate and animate the rotation by using the
camorbit() command.
figure(4); % bring this figure to the foreground.
axis vis3d % allow for rigid 3d rotation
for i=1:36 % change camera angle 36 times
camorbit(10,0,'camera') % 10 degree increments
pause(0.01); % slow it down slightly
end
close(4);

We can also create a movie by capturing frames using the getframe() command and playing them
with the movie() function. Alternatively we can create an avi file with the avifile() , and addframe()
functions. Read their help entries for more information and examples.

There are many other functions that can be used to adjust the camera angle and motion such as
camdolly() , campan() , camzoom() , and camroll() .

advancedmcode.org/plotting-in-matlab.… 18/28
12/17/2010 Plotting in Matlab

User Input & Callbacks


Matlab has good support for the creation of graphical user interfaces. To launch an interactive GUI
builder, type guide at the command prompt. Here, we will only briefly touch on some of the ways in
which users can interact with figures. To learn more about creating GUIs type doc guide and click
on “Creating GUIs” at the bottom of the help page.

We will begin by discussing the ginput() function, which returns a matrix of coordinates selected with
the mouse. Let’s bring up the second plot we made, call ginput() and select a few data points to
return their coordinates. ginput(n) waits for n user clicks before returning the n points, whereas
ginput() , without any parameters, allows you to select any number you like and returns only when
the user presses the enter key. A similar function, gtext(txt) places the specified string at the location
selected by the mouse.
figure(f1);
C = ginput(5)
close(f1);

C=
1.8468 1.2719
1.7984 1.3947
1.7984 1.6053
1.8790 1.7281
2.1855 1.7105

The above functions operate by assigning a callback function to the axes object, which gets executed
whenever the user clicks within the axes. We can assign our own function to perform whatever action
we wish when this happens. Most Matlab graphics objects have callback attributes, which can be
viewed using the get() command and set using set() .

The only constraint on callback functions is that they take 3 or more parameters as in
myCallback(hObject, eventdata, handles): hObject is the object selected, whereas eventdata, and
handles differ depending on the the callback. For more information, search for CallBack Syntax and
Arguments in help.

All graphics objects in Matlab also have a ‘UserData’ attribute, which can be assigned any data you
like. Since the clicked object is returned in hObject, we can retrieve this data with
get(hObject,’UserData’).

In this simple example, we plot 5 points in 5 different plots and assign each plot’s ‘UserData’ attribute
a color’s name, which we will display when clicked. Since this is a simple example, we can create the
callback inline but in general you should create a stand alone function say function
myCallback(hObject,eventData,handles) and then assign @myCallback to the object’s callback
attribute. We also assign the callback to the current axes and figure objects after setting their
‘UserData’ entries to their respective colors. Try out the code for yourself.
figure;
hold all;
name = {'red','blue','green','magenta','cyan'};
color = {'.r','.b','.g','.m','.c'};
loc = [(1:5)',2*ones(5,1)];
callback = @(hObject,eventData,handles)display(get(hObject,'UserData'));
for i=1:numel(name)
plot(loc(i,1),loc(i,2),color{i},...
'MarkerSize',100,'UserData',name{i},...
advancedmcode.org/plotting-in-matlab.… 19/28
12/17/2010 Plotting in Matlab
'ButtonDownFcn',callback);
end
axis([0,6,1,3]);
set(gca,'UserData','white') % Set the axes user data
set(gca,'XTick',[],'YTick',[],'box','on');
set(gca,'ButtonDownFcn',callback); % assign the callback
set(gcf,'UserData','grey'); % set the figure user data
set(gcf,'ButtonDownFcn',callback); % assign the callback

Custom Functions
When many figures are generated at once, it can be difficult to organize them all on the screen. The
placeFigures() function, available below automatically organizes figures on the screen for you. Simply
call placeFigures after generating the figures. You can specify the layout manually with say
placeFigures(‘nrows’,2,’ncols’,4) , create new blank figures with the ‘newfigs’ option and display
figures on a second monitor with the ‘monitor’ option. See the function documentation for more
options and examples.

placeFigures.m

(x,y) Data Digitizing www.digitizeit.de


Digitize any plot into (x,y)-data. Automatically!
Free trial.
CAD Viewer - Download www.oracle.com/autovue
AutoVue: View-Markup 2D/3D & EDA CAD
formats. Download & try it.
Graphing Calculator 3D calculator.runiter.com
Best 3D grapher in the world! Download it for
free.
Try mini-graphs in Excel www.bissantz.de
Bissantz SparkMaker for Excel dashboards and
advancedmcode.org/plotting-in-matlab.… 20/28
12/17/2010 Plotting in Matlab
Bissantz SparkMaker for Excel dashboards and
reports - free trial

Rating: 9.9/10 (10 votes cast)


Rating: +6 (from 6 votes)

Popularity: 2% [?]

Share and Enjoy:

Related Posts

No Related Post

Tags: matlab graph, matlab plot, plotting

Comments

6 Comments on Plotting in Matlab

1. Boshra Vafaie on Mon, 21st Jun 2010 09:20

Dear sir
i really nead to have Matlab cods to plot some CTD data`s contours and section plots, how do i
can do it? could you help me please?
we have many stations which given by CTD, and i must analysis these data but first of all i
should plot the graphs and Contours in matlab.

thank you so much


Boshra Vafaie
boshra_vafaie@yahoo.com

[Reply]

Rating: 1.0/5 (1 vote cast)


Rating: 0 (from 0 votes)

2. Julian Mulla on Thu, 24th Jun 2010 18:00

Good tutorial. Coordinate conversion, function [xabs,yabs] = rel2abs(xpos,ypos), is very useful


but didn’t quite worked for me on chart with datetime X axis. Instead I’d suggest looking at the
matlab’s provided function dsxy2figxy
advancedmcode.org/plotting-in-matlab.… 21/28
12/17/2010 Plotting in Matlab
For more information see:
http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/bquk5ia-1.html

[Reply]

Rating: 0.0/5 (0 votes cast)


Rating: 0 (from 0 votes)

3. Joe Lotz on Thu, 1st Jul 2010 05:25

Nice article! It makes me think of making “tool-tips” on images with dimensional values.

Does anyone know of a way to change the alpha value on plot or scatter functions? I’ve been
able to make circular patches and change value but this doesn’t work with non-square axis.

Thanks!

[Reply]

Rating: 0.0/5 (0 votes cast)


Rating: 0 (from 0 votes)

4. karen on Tue, 17th Aug 2010 02:49

Good day sir!

I just want to ask regarding a particular programming assignment using MATLAB.

We are required to make a program that will implement AM,FM, and PM signals. For each
categories-AM,FM, and PM, we will be creating a function of two inputs, say m(t) for message
signal and c(t) for the carrier. In the command window, the user will just input the two
necessary parameters and later on will call the functions. Each function must plot the modulated
waveforms of the given input. The time to be use depends on the programmer. I have a
difficulty doing such assignment as I am not good at programming.

Thank you so much and more power.

[Reply]

Rating: 0.0/5 (0 votes cast)


Rating: 0 (from 0 votes)

advancedmcode.org/plotting-in-matlab.… 22/28
12/17/2010 Plotting in Matlab
5. ronnit on Mon, 1st Nov 2010 13:22

matlab is my favrout sofware but so many problem creatd when i m working because m
comparing this mtlab to my fx-991ms clc so mainy similar .i wanna make some new things can
u help me…..rply me

[Reply]

Rating: 0.0/5 (0 votes cast)


Rating: 0 (from 0 votes)

6. Ramesh on Tue, 7th Dec 2010 08:47

Hi

Thanks for your post. I have saved it for future reference.

I have a query wherein I could use your expert help. I have a program in which the user
chooses certain points on an image and a region/ polygon depicting the chosen points as
connected vertices is drawn. I want that region to have grid lines in it. These lines should be
confined to the chosen region only.

I searched the documentation and ran into meshgrid. Is there some sort of function for a grid
in 2 dimensions? Something like the graph you have shown titled Interpolation, but with that
gridded surface on the X-Y plane?

Thanks

[Reply]

Rating: 0.0/5 (0 votes cast)


Rating: 0 (from 0 votes)

Tell me what you're thinking...


and oh, if you want a pic to show with your comment, go get a gravatar!

Include MATLAB code in your comment by doing the following:

<pre lang="MATLAB">

%insert code here

</pre>
advancedmcode.org/plotting-in-matlab.… 23/28
12/17/2010 Plotting in Matlab

Name (required)

Email Address (required)

Website

Speak your mind

Submit Comment

c
d
e
f
g Notify me of followup comments via e-mail

Recent Posts
A Freeware ToolBox for Surface Reconstruction
FreeWare Surface Reconstruction ToolBox: Testools
The Effect of the Ball Radius in the BallPivoting
Reconstructing a 1M Point Cloud With SCBMesher
Fourier-Bessel Transform for Face Recognition
Speaker Recognition based on Relative Spectral Methodology
Open Source Fluid-Structure Interaction, chaining Code_Aster and Code_Saturne
Statistical Moments for Pattern Recognition
Fast and Accurate Iris Segmentation
Iris Recognition Using Wavelet Features

Most rated
7.5: MATLAB for Digita ... (20 votes)
9.8: Object Oriented P ... (16 votes)
8.6: How to create a K ... (10 votes)
9.9: Plotting in Matla ... (10 votes)
8.3: ROC curve (8 votes)
6.6: MATPOWER: A MATLA ... (8 votes)
10.0: Poker Predictor: ... (8 votes)
6.8: ASK, OOK, FSK, BP ... (8 votes)

advancedmcode.org/plotting-in-matlab.… 24/28
12/17/2010 Plotting in Matlab
9.3: Surface Reconstru ... (8 votes)
8.6: Poker Predictor: ... (7 votes)
8.1: Surface Reconstru ... (7 votes)
8.4: Flow of Control a ... (7 votes)
9.2: Quick Delaunay Tr ... (6 votes)
10.0: Open Source Fluid ... (5 votes)
10.0: GLTree:Fast K-Nea ... (5 votes)

Popular Posts
A Freeware Tool... 104 view(s) per day
Plotting in Mat... 92 view(s) per day
Matlab and Micr... 73 view(s) per day
Object Oriented... 60 view(s) per day
ASK, OOK, FSK, ... 59 view(s) per day
MATLAB for Digi... 57 view(s) per day
How to create a... 45 view(s) per day
The Matlab Matr... 39 view(s) per day
ROC curve 38 view(s) per day
Surface Reconst... 37 view(s) per day
FreeWare Surfac... 35 view(s) per day
Optical Charact... 35 view(s) per day
Reconstructing ... 33 view(s) per day
Writing Fast Ma... 32 view(s) per day
Interfacing MAT... 29 view(s) per day
Free Open Sourc... 28 view(s) per day
Strings, Cells,... 27 view(s) per day
Writing and Usi... 26 view(s) per day
How to plot a c... 25 view(s) per day
Fourier-Bessel ... 23 view(s) per day
Fast Convex Hul... 22 view(s) per day
Poker Predictor... 22 view(s) per day
Surface Reconst... 21 view(s) per day
Unstructured 2D... 19 view(s) per day
Open Source Flu... 18 view(s) per day

Tags

2d 3D advanced matlab code ann cards Convex Hull dct delaunay Delaunay2.5D Delaunay2_5D detection editbox face
matching Face recognition fast matlab code feature extraction FEM filter function GLTree Graphics
GUI Example identification Image processing iris manifold matching Matlab source code
image

mesh nearest neighbor nearest neighbour neural networks Poker popup pushbutton.
network PCA

recognition scanner 3D String surface surface reconstruction System


strain stress Texas

Holdem text verification Wavelet

Category Cloud
advancedmcode.org/plotting-in-matlab.… 25/28
12/17/2010 Plotting in Matlab
Logistics Jav a Genetic Media MEX science python Fun linux CFD Electronic Neural Network W eb Whatev er Linear A lgebra Medicine Electric
Mechanics Physics Sound technology C Games Economy Biotecnology Numerical A naly sis Geometry FEM Probability Optimization
Mathematics Statistics Signal Processing NewsGroup CAD General Utility Graphics Code Optimization GUI
Algorithms Computational Geometry Image processing Tutorials

Recent Comments
beceteemi on CONV2 Overlap-add Method
Luigi Giaccari on A Freeware ToolBox for Surface Reconstruction
Emiliano on A Freeware ToolBox for Surface Reconstruction
Luigi Giaccari on A Freeware ToolBox for Surface Reconstruction
Emiliano on A Freeware ToolBox for Surface Reconstruction
ija hashim on Surface Reconstruction from Scattered Points Cloud: MyCrust Robust
Feng on GLTree:Fast K-Nearest Neighbors Search
Ramesh on Plotting in Matlab
Luigi Giaccari on The Fastest way to sort 3 values
JohnPaul Adamovsky on The Fastest way to sort 3 values

Search
Search

Translator

Make a contribution

Log-In/Register
Start posting on Advanced M-code!

Register

Log In
advancedmcode.org/plotting-in-matlab.… 26/28
12/17/2010 Plotting in Matlab

Follow Us

Facebook

Twitter

By Email

Entries RSS

Comment RSS

Blogroll
advancedsourcecode
Online Foreign exchange
Statistical Consulting
Undocumented Matlab
walkingrandomly
Ads by Google
3D Graph
2D 3D Design Software
Graph Plot
3D Plotter

Video Posts

Archives
December 2010 (5)

advancedmcode.org/plotting-in-matlab.… 27/28
12/17/2010 Plotting in Matlab
November 2010 (4)
October 2010 (4)
September 2010 (5)
August 2010 (2)
July 2010 (7)
June 2010 (11)
May 2010 (17)
April 2010 (11)
March 2010 (13)
February 2010 (29)
January 2010 (21)
December 2009 (16)
November 2009 (18)
October 2009 (21)
September 2009 (12)
August 2009 (28)

Pages
Infos
Writing Post (Tutorial)
Submit
Books
Commercial Softwares
Papers
Posts Directory

StatPress
Visits Today: 69
Visits Last Month: 17244
Visitors on line: 3

Meta
Register
Log in
Entries RSS
Comments RSS
WordPress.org

Copyright © 2008 · Revolution Code Blue theme by Brian Gardner - Thanks to NLC

Get a Blog · WordPress · Log in

advancedmcode.org/plotting-in-matlab.… 28/28

S-ar putea să vă placă și