100% found this document useful (1 vote)
132 views34 pages

Graphics: by J.S. Park Incheon National University

This document provides an overview of plotting in MATLAB, including: - The basic process of creating and editing graphs through plotting commands and tools. - Common graph types like lines, bars, histograms, and 3D graphs that can be created. - Basic plotting functions for customizing graphs, like plot, semilogx, grid, title, xlabel, ylabel, and hold. - Additional functions for annotating graphs, controlling the figure window and axes, and displaying multiple plots.

Uploaded by

라네
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
100% found this document useful (1 vote)
132 views34 pages

Graphics: by J.S. Park Incheon National University

This document provides an overview of plotting in MATLAB, including: - The basic process of creating and editing graphs through plotting commands and tools. - Common graph types like lines, bars, histograms, and 3D graphs that can be created. - Basic plotting functions for customizing graphs, like plot, semilogx, grid, title, xlabel, ylabel, and hold. - Additional functions for annotating graphs, controlling the figure window and axes, and displaying multiple plots.

Uploaded by

라네
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/ 34

Chapter 03:

Graphics

By J.S. Park
Incheon National University
Overview of Plotting
Plotting Process
• display data graphically.
• annotate and print graphs for presentations.

Creating a Graph
• line, bar, histogram, pie graphs, and 3-D graphs, such as surfaces, slice planes, and streamlines.
• Two basic ways to create MATLAB graphs:
- Use plotting tools.
- Enter commands in the Command Window or create plotting programs.
• combine both approaches
- a plotting command to create a graph and then modify the graph using the interactive
tools.

Editing the Graph Components


• You can change graphs.
- the axes, the scale, color, line style, type of marker, etc.

Annotating Graphs
• Annotations are the text, arrows, and other labels added to graphs
Basic Plotting Functions
plottools Show or hide the plot-editing tools for a figure. (plottools, plottools on, plottools off)
plot PLOT(X,Y) plots vector Y versus vector X.
semilogx Same as plot except logarithmic (base 10) scale is used for the X-axis
semilogy Same as plot except logarithmic (base 10) scale is used for the Y-axis
loglog Same as plot except Logarithmic scales are used for both the X- and Y- axes
plotyy Graphs with y tick labels on the left and right
PLOTYY(X1,Y1,X2,Y2) plots Y1 versus X1 with y-axis labeling on the left and
plots Y2 versus X2 with y-axis labeling on the right.
plot3 Plot lines and points in 3-D space. PLOT3() is a three-dimensional analogue of PLOT().
PLOT3(x,y,z), where x, y and z are three vectors of the same length, plots a line in
3-space through the points whose coordinates are the elements of x, y and z.
grid Grid lines. (grid, grid on, grid off)
title title('text') adds text at the top of the current axis.
xlabel xlabel('text') adds text beside the X-axis on the current axis.
ylabel ylablel('text') adds text beside the Y-axis on the current axis.
axis Control axis scaling and appearance.
axis([XMIN XMAX YMIN YMAX]) sets scaling for the x- and y-axes on the current plot.
axis([XMIN XMAX YMIN YMAX ZMIN ZMAX]) sets the scaling on the current 3-D plot.
axes AXES, by itself, creates the default full-window axis and returns a handle to it.
hold Hold current graph, so that subsequent graphing commands add to the existing graph.
(hold, hold on, hold off)
legend legend(string1,string2,string3, ...) puts a legend on the current plot using the specified strings as
labels.
legend off removes the legend from the current axes and deletes the legend handle.
subplot H = subplot(m,n,p), or subplot(mnp), breaks the Figure window into an m-by-n matrix of small axes,
selects the p-th axes for the current plot, and returns the axis handle.
Graph Components
MATLAB graphs display in a special window known as a figure.
x = -10:.005:40;
y = [1.5*cos(x)+4*exp(-.01*x).*cos(x)+exp(.07*x).*sin(3*x)];
plot(x,y)
title ('y = 1.5cos(x) + 4e^{-0.01x}cos(x) + e^{0.07x}sin(3x)')
xlabel('X Axis')
ylabel('Y Axis')
Script M-file

Script M-file
File name is fig_example.m

1 Create an M-file % script M-file of Figure Example


using a text editor: x = -10:.005:40;
y = [1.5*cos(x)+4*exp(-.01*x).*cos(x)+exp(.07*x).*sin(3*x)];
plot(x,y)
title ('y = 1.5cos(x) + 4e^{-0.01x}cos(x) + e^{0.07x}sin(3x)')
xlabel('X Axis')
ylabel('Y Axis')

2 Call the M-file from the


command line, or from
within another M-file. >>fig_example
linspace Linearly spaced vector.
linspace(X1, X2) generates a row vector of 100 linearly equally spaced points between X1 and X2.
linspace(X1, X2, N) generates N points between X1 and X2. For N < 2, LINSPACE returns X2.
logspace Logarithmically spaced vector.
logspace(X1, X2) generates a row vector of 50 logarithmically equally spaced points between
decades 10^X1 and 10^X2. If X2 is pi, then the points are between 10^X1 and pi.
logspace(X1, X2, N) generates N points. For N < 2, LOGSPACE returns 10^X2.

x = logspace(-2,3,1000);
y = sqrt(x);
semilogx(x,y)
grid
Using Basic Plotting Functions
Creating a Plot Plotting Multiple Data Sets in One Graph

x = 0:pi/100:2*pi; x = 0:pi/100:2*pi;
y = sin(x); y = sin(x);
plot(x,y) y2 = sin(x-.25);
xlabel('x = 0:2\pi') y3 = sin(x-.5);
ylabel('Sine of x') plot(x,y,x,y2,x,y3)
title('Plot of the Sine Function','FontSize',12)
The legend command provides an easy way
to identify the individual plots:
legend('sin(x)','sin(x-.25)','sin(x-.5)')
Specifying Line Styles and Colors
plot(x,y,'color_style_marker‘) Plotting Lines and Markers
plot(x,y,'ks')
plots black squares at each data point.
plot(x,y,'r:+')
plots a red-dotted line and places plus sign markers at each
data point.

Placing Markers at Every Tenth Data Point


points for the dotted line and marker plots:
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Graphing Imaginary and Complex Data
When the arguments to plot are complex,
A graph of the real part versus the imaginary part.

plot(Z)

where Z is a complex vector or matrix, is equivalent to

plot(real(Z),imag(Z))

For example,

>>t = 0:pi/10:2*pi;
>>plot(exp(i*t),'-o')
>>axis equal

axis equal command makes the individual


tick-mark increments on the x- and y-axes the
same length, which makes this plot more
circular in appearance.
Figure Windows
Displaying Multiple Plots in One Figure
figure Open a new figure window and
make it the current figure, subplot(m,n,p)
figure(n) Make an existing figure window the
current figure, where n is the number in partitions the figure window into an m-by-n
the figure title bar. matrix of small subplots and selects the pth
subplot
clf reset Clearing(Resetting) the Figure for a New
Plot
x = -1:.1:1;
close n Close the figure, where n is the figure y1= x.^2;
handle
y2= x.^3;
close all Close all figure y3= x.^4;
y4= x.^5;
hold on Adding Plots to an Existing Graph
subplot(2,2,1);
hold off rescaling the axes if necessary. plot(x,y1);
subplot(2,2,2);
x = -1:.1:1;
plot(x,y2);
y = x.^3;
plot(x,y); subplot(2,2,3);
hold on plot(x,y3);
y = x.^4; subplot(2,2,4);
plot(x,y,‘r’); plot(x,y4);
hold off

subplot(1,1,1)
Controlling the Axes
The axis command provides options for setting the scaling, orientation, and aspect ratio of graphs.

Setting Axis Limits


By default, MATLAB finds the maxima and minima of the data and chooses the axis limits to span this range.
axis([xmin xmax ymin ymax])
or for three-dimensional graphs,
axis([xmin xmax ymin ymax zmin zmax])
To enable automatic limit selection again,
axis auto

Setting the Axis Aspect Ratio plot(exp(i*[0:pi/10:2*pi]))


To makes the x-axis and y-axis the same length ,
axis square followed by either
To makes the individual tick mark increments on the x-axes and y-axes the same length, axis square or
axis equal
axis equal
turns the oval into a
To return the axis scaling to its default automatic mode,
proper circle:
axis auto normal

Setting Axis Visibility Setting Grid Lines


To make the axis visible, The grid command toggles grid lines on and off.
axis on
To makes the axes invisible, To turn the grid lines on,
axis off grid on
To turn the grid lines off,
grid off
Adding Axis Labels and Titles
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels.
The title command adds a title at the top of the figure and
the text function inserts text anywhere in the figure.
You can produce mathematical symbols using LaTeX notation in the text string.

t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi pi -1 1])
xlabel('-\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'{\itNote the odd symmetry.}')
plot3 for 3-D Plots
x=0:0.1:100;
y=sin(x);
z=cos(x);
plot3(x,y,z)
grid

0.5

-0.5

-1
1
0.5 100
80
0 60
-0.5 40
20
-1 0
Figure Tools
Figure Tools

Accessing the Tools

Figure Toolbars

Plotting Tools

 You can also start the plotting tools from the MATLAB prompt:
plottools
Plotting Tools
The plotting tools are made up of three independent GUI components:
• Figure Palette — Specify and arrange subplots, access workspace variables for plotting or editing, and
add annotations.
• Plot Browser — Select objects in the graphics hierarchy, control visibility, and add data to axes.
• Property Editor — Change key properties of the selected object.

You can also control these components from the Command Window, by typing the following:
figurepalette
plotbrowser
propertyeditor
Using Plotting Tools and MATLAB Code

t = 0:pi/20:2*pi;
y = exp(sin(t));
plotyy(t,y,t,y,'plot','stem')
xlabel('X Axis')
ylabel('Plot Y Axis')
title('Two Y Axes')

This graph contains two y-axes,


one for each plot type
- lineseries and
- a stemseries

Arranging Graphs Within a Figure

Choosing a Type of Graph to Plot


2-D and 3-D graphs
Creating Graphs with the Plot Selector
• Select variables in the Workspace Browser,
• Create a graph of the data by clicking the Plot Selector toolbar button.

• For example, when you select two vectors named t and y, the Plot Selector initially
displays plot(t,y).

• If you click the down-arrow on the right side of the button, its menu opens to display
all graph types compatible with the selected variables.
Creating Graphs with the Plot Catalog

Instead of the Plot Selector,


you can use the Plot Catalog
tool to create the Plot.

Open the Plot Catalog:


• Open the Plot Selector menu
and click the Catalog link at the
bottom of the menu.
• In the Workspace browser,
right-click a selected variable and
choose Plot Catalog from the
context menu.
• In the Variable Editor,
select the values you want to
graph, right- click the selection
you just made, and choose Plot
Catalog from the context menu.
• If you are using the Figure
Palette, right-click a selected
variable and choose Plot Catalog
from the context menu
Editing Plots
Enabling Plot Edit Mode

Setting Object Properties


You can select objects by clicking them in the graph.
Selection handles appear and indicate that the object is selected.
Select multiple objects using Shift+click.
Right-click with the pointer over the selected object to display
the object’s context menu

Accessing Properties with the Property Inspector


click the More Properties button to display the Property Inspector.
Also, to inspect the properties of the current axes, you can type
inspect(gca) you can group Handle Graphics
objects, such as axes, by categories

To do so, click the icon at the


upper left, then click the + next to
the category you want to expand.

The properties of a graph’s axes.


Some Ways to Use Plotting Tools
Plotting Two Variables with Plotting Tools

graph the function y = x3 over the x domain -1 to 1.

x = -1:.1:1; % Define the range of x


y = x.^3; % Raise each element in x to the third power

To start the plotting tools, type


>>plottools

select both variables


and then right-click to display the context menu.

Select plot(x, y) from the menu.


Changing the Appearance of Lines and Markers
Use the Property Editor to set following properties:
• Line to no line
• Marker to o (circle)
• Marker size to 4.0
• Marker fill color to red

Adding More Data to the Graph


Select the axes in the Plot Browser and click the Add Data button.
When you are using the plotting tools, new data plots are always added to
the existing graph, instead of replacing the graph,
as it would if you issued repeated plotting commands.
1 Click the Edit Plot tool .
2 Select the axes to which you wish to add data; handles appear around it.
3 Click the Add Data button in the Plot Browser; the Add Data to Axes dialog box opens.
4 Select a plot type from the Plot Type drop-down menu.
5 Select a variable or type an expression for X Data Source.
6 Select a variable or type an expression for Y Data Source.
7 Click OK;

y = x4
is added to the
existing plot of
y = x3.
Changing the Type of Graph
1 Select both plotted series in the Plot Browser or
Shift+click to select them in the plot itself.
2 Select short dashes from the Line drop-down menu in the Property Inspector;
the line type of both series changes.
3 Select Stem from the Plot Type menu.
Modifying the Graph Data Source
>>x = linspace(-3*pi,3*pi,50); % Define 50 points between -3*pi and 3*pi
>>ys = sin(x); >>yc = cos(x);
>>figure

In the Figure Palette, select x and ys in the Variable pane.


Right-click either selected variable and choose plot(x, ys) from the
context menu

To change the data that this plot displays:


1 In the Figure Palette, select x and yc in the Variable pane.
2 Right-click either selected variable and choose plot(x, ys) from the
context menu. The plot will change to display a plot of yc vs x.

To change the data source:


Select the blue line on the plot.
Select, x as the X Data Source, y as the Y Data Source,
and click Refresh Data.
The graph’s XData and YData are replaced.

Data Source
>>x = linspace(-pi,pi,50);
>>y = sin(x);
>>area(x,y) % Make an area plot of x and y
Now, recalculate y at the command line:
>>y = cos(x)
Select the blue line on the plot. Select, x as the X Data
Source, y as the Y Data Source, and click Refresh Data.
The graph’s XData and YData are replaced.
Annotating Graphs for Presentation

x = -10:.005:40; Data tips using the Data Cursor tool


y = [1.5*cos(x)+4*exp(-.01*x).*cos(x)+ ... Zoom tool
Left-clicking the line moves the last
exp(.07*x).*sin(3*x)]; Pan tool
datatip you created
to position the points of interest
plot(x,y) To create a new datatip, press Alt+click or
use the tool’s context menu.

Axis labels:
title ('y = 1.5cos(x) + 4e^{-0.01x}cos(x) …
Use the Figure Palette to annotate the plot. + e^{0.07x}sin(3x)')
Add a text box, using the Figure Palette.
Choose the Double arrow tool in the xlabel('X Axis')
Use the Property Editor to change the
Annotations section to draw a line between ylabel('Y Axis')
text style,.
two datatips.
Printing the Graph
File > Print Preview to view and modify

• Lines/Text tab,
- enter a line of text in the Header Text edit field
- font, style, and size of the header, date format
• The rulers along the left and top sides of the preview pane.
- stretch one edge of the plot, leaving the other edges in place.
- The inner handlebars let you move the plot up and down or left and right without stretching it.
- does not affect the figure itself, only the printed version of it.

• Layout tab
-change the size and
position of the plot on the
page using the buttons and
edit boxes.
-You can revert to the
original configuration by
clicking the Auto (Actual
Size, Centered) option
button,
-correct stretching and
shrinking by clicking Fix
Aspect Ratio.
Exporting the Graph
Creating a standard graphics file format of the graph (such as EPS or TIFF)
This example:
- Exports the graph as an EPS file
- The size : 4 inches wide and 3 inches high.
- All the text in the figure : a size of 8 points.

Specifying the Size of the Graph


- Select Export Setup from the figure File menu
- select 4 from the Width list and 3 from the Height list.

Specifying the Font Size


- select Fonts in the Export Setup dialog box Properties selector.
- Click Use fixed font size and enter 8 in the text box.
Saving Figures
Save a figure by selecting Save from the File menu.

Saving Workspace Data

You can save the variables in your workspace by selecting Save Workspace As
from the figure File menu.

You can reload saved data using the Import Data item in the figure File menu.
- MATLAB data files, which have a .mat extension.

Generating M-Code to Recreate a Figure

You can generate MATLAB code that recreates a figure and the graph it contains by selecting
Generate M-File from the figure File menu.
Creating Mesh and Surface Plots
About Mesh and Surface Plots
• You define a surface by the z-coordinates of points above a grid in the x-y plane.
• The mesh and surf plotting functions display surfaces in three dimensions.
• mesh produces wireframe surfaces that color only the lines connecting the defining points.
• surf displays both the connecting lines and the faces of the surface in color.
• The figure colormap and figure properties determine how the surface is colored.

Example — Graphing the sinc Function


Evaluates and graphs the two-dimensional sinc function,
sin(r)/r, between the x and y directions.
R is the distance from the origin, which is at the center
of the matrix.
Adding eps (a small floating-point number) avoids the
indeterminate 0/0 at the origin:

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black‘)

A mesh with see-through faces by disabling hidden line


removal:
hidden off
Example — Colored Surface Plots
A surface plot is similar to a mesh plot except that the rectangular faces of the surface are
colored.
The color of each face is determined by the values of Z and the colormap (a colormap is an
ordered list of colors).
These statements graph the sinc function as a surface plot, specify a colormap, and add a color
bar to show the mapping of data to color:

surf(X,Y,Z)
colormap hsv
colorbar
Making Surfaces Transparent
You can make the faces of a surface transparent to a varying degree.
Transparency (referred to as the alpha value) can be specified for the whole object or can be
based on an alphamap.
For example,

surf(X,Y,Z)
colormap hsv
alpha(.4)

produces a surface with


a face alpha value of 0.4.
Alpha values range from
0 (completely transparent) to
1 (not transparent).
Illuminating Surface Plots with Lights
Lighting is the technique of illuminating an object with a directional light source.
This technique can make subtle differences in surface shape easier to see.
Lighting can also be used to add realism to three-dimensional graphs.
This example uses the same surface as the previous examples, but colors it
red and removes the mesh lines. A light object is then added to the left of the Creating Mesh
and Surface Plots “camera” (the camera is the location in space from where you are viewing
the surface):
surf(X,Y,Z,'FaceColor','red','EdgeColor','none')
camlight left; lighting phong
Manipulating the Surface
The figure toolbar and the camera toolbar provide ways to explore 3-D graphics interactively.
Display the camera toolbar by selecting Camera Toolbar from the figure View menu.
The following picture shows both toolbars with the Rotate 3D tool selected.

These tools enable you to move the camera around the surface object, zoom, add lighting, and
perform other viewing operations without issuing commands.
Plotting Image Data
About Plotting Image Data
Two-dimensional arrays can be displayed as images, where the array elements determine brightness or color of
the images.
For example, the statements
>>load durer
>>whos
Name Size Bytes Class
X 648x509 2638656 double array
caption 2x28 112 char array
map 128x3 3072 double array

X is a 648-by-509 matrix of the image. Integers between 1 and 128.


map is a 128-by-3 matrix that is the colormap for this image.

>>image(X)
>>colormap(map)
>>axis image

reproduces Albrecht Dürer’s etching.


A high-resolution scan of the magic square in the upper-right corner is available in another file.
detail.mat

colormap(hot) adds some 21st century colorization to the 16th century etching.
See the colormap reference page for a list of other predefined colormaps.
Reading and Writing Images
imread function : read standard image files (TIFF, JPEG, BMP, etc)

>> imread('c:\windows\bamboo2.jpg');
>> image(ans)
>> axis image

imwrite function : write MATLAB data to a variety of standard


image formats.

imwrite(A,FILENAME,FMT)
A – variable name,
FILENAME – file name
FMT - format specified

>> imwrite(ans, 'bamboo.jpg', 'JPEG')

You might also like