| MATLAB® | ![]() |
| On this page… |
|---|
Plotting Multiple Data Sets in One Graph Specifying Line Styles and Colors Graphing Imaginary and Complex Data Adding Plots to an Existing Graph |
The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
For example, these statements use the colon operator to create a vector of x values ranging from 0 to 2π, compute the sine of these values, and plot the result:
x = 0:pi/100:2*pi; y = sin(x); plot(x,y)
Now label the axes and add a title. The characters \pi create the symbol π. See "text strings" in the MATLAB Reference documentation for more symbols:
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

Multiple x-y pair arguments create multiple graphs with a single call to plot. automatically cycle through a predefined (but customizable) list of colors to allow discrimination among sets of data. See the axes ColorOrder and LineStyleOrder properties.
For example, these statements plot three related functions of x, with each curve in a separate distinguishing color:
x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x-.25); y3 = sin(x-.5); plot(x,y,x,y2,x,y3)
The legend command provides an easy way to identify the individual plots:
legend('sin(x)','sin(x-.25)','sin(x-.5)')

For More Information See Defining the Color of Lines for Plotting in the MATLAB Graphics documentation. |
It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot your data using the plot command:
plot(x,y,'color_style_marker')color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type. The strings are composed of combinations of the following elements:
| Type | Values | Meanings |
|---|---|---|
| Color | 'c' 'm' 'y' 'r' 'g' 'b' 'w' 'k' | cyan magenta yellow red green blue white black |
| Line style | '-' '--' ':' '.-' no character | solid dashed dotted dash-dot no line |
| Marker type | '+' 'o' '*' 'x' 's' 'd' '^' 'v' '>' '<' 'p' 'h' no character or none | plus mark unfilled circle asterisk letter x filled square filled diamond filled upward triangle filled downward triangle filled right-pointing triangle filled left-pointing triangle filled pentagram filled hexagram no marker |
You can also edit color, line style, and markers interactively. See Editing Plots for more information.
If you specify a marker type but not a line style, only the marker is drawn. For example,
plot(x,y,'ks')
plots black squares at each data point, but does not connect the markers with a line.
The statement
plot(x,y,'r:+')
plots a red-dotted line and places plus sign markers at each data point.
You might want to use fewer data points to plot the markers than you use to plot the lines. This example plots the data twice using a different number of 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+')

When the arguments to plot are complex, the imaginary part is ignored except when you pass plot a single complex argument. For this special case, the command is a shortcut for a graph of the real part versus the imaginary part. Therefore,
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
draws a 20-sided polygon with little circles at the vertices. The 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.

The MATLAB hold command enables you to add plots to an existing graph. When you type
hold on
Now MATLAB does not replace the existing graph when you issue another plotting command; it adds the new data to the current graph, rescaling the axes if necessary.
For example, these statements first create a contour plot of the peaks function, then superimpose a pseudocolor plot of the same function:
[x,y,z] = peaks; pcolor(x,y,z) shading interp hold on contour(x,y,z,20,'k') hold off
The hold on command combines the pcolor plot with the contour plot in one figure.

For More Information See Creating Specialized Plots in the MATLAB Graphics documentation for details about a variety of graph types. |
Graphing functions automatically open a new figure window if there are no figure windows already on the screen. If a figure window exists, it is used for graphics output. If there are multiple figure windows open, the one that is designated the "current figure" (the last figure used or clicked in) is used. See documentation for the gcf function for more information.
To make an existing figure window the current figure, you can click the mouse while the pointer is in that window or you can type
figure(n)
where n is the number in the figure title bar. The results of subsequent graphics commands are displayed in this window.
To open a new figure window and make it the current figure, type
figure
When a figure already exists, most plotting commands clear the axes and use this figure to create the new plot. However, these commands do not reset figure properties, such as the background color or the colormap. If you have set any figure properties in the previous plot, you might want to use the clf command with the reset option,
clf reset
before creating your new plot to restore the figure's properties to their defaults.
For More Information See Figure Properties and Graphics Windows — the Figure in the MATLAB Graphics documentation for details about figures. |
The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along the first row of the figure window, then the second row, and so on. For example, these statements plot data in four different subregions of the figure window:
t = 0:pi/10:2*pi; [X,Y,Z] = cylinder(4*cos(t)); subplot(2,2,1); mesh(X) subplot(2,2,2); mesh(Y) subplot(2,2,3); mesh(Z) subplot(2,2,4); mesh(X,Y,Z)

You can add subplots to GUIs as well as to figures. For details about creating subplots in a GUIDE-generated GUI, see Creating Subplots in the MATLAB Creating Graphical User Interfaces documentation.
The axis command provides a number of options for setting the scaling, orientation, and aspect ratio of graphs. You can also set these options interactively. See Editing Plots for more information.
By default, MATLAB finds the maxima and minima of the data and chooses the axis limits to span this range. The axis command enables you to specify your own limits:
axis([xmin xmax ymin ymax])
or for three-dimensional graphs,
axis([xmin xmax ymin ymax zmin zmax])
Use the command
axis auto
to enable automatic limit selection again.
The axis command also enables you to specify a number of predefined modes. For example,
axis square
makes the x-axis and y-axis the same length.
axis equal
makes the individual tick mark increments on the x-axes and y-axes the same length. This means
plot(exp(i*[0:pi/10:2*pi]))
followed by either axis square or axis equal turns the oval into a proper circle:
axis auto normal
returns the axis scaling to its default automatic mode.
You can use the axis command to make the axis visible or invisible.
axis on
makes the axes visible. This is the default.
axis off
makes the axes invisible.
The grid command toggles grid lines on and off. The statement
grid on
turns the grid lines on, and
grid off
turns them back off again.
For More Information See the axis and axes reference pages and Axes Properties in the MATLAB Graphics documentation. |
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, as the following example illustrates:
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.}')

You can also set these options interactively. See Editing Plots for more information.
Note that the location of the text string is defined in axes units (i.e., the same units as the data). See the annotation function for a way to place text in normalized figure units.
Save a figure by selecting Save from the File menu to display a Save dialog box. This saves the figure, the data within it, and all annotations (i.e., the entire graph) in a file with a .fig extension.
To save a figure using a standard graphics format, such as TIFF, for use with other applications, select Export Setup from the File menu. You can also save from the command line—use the saveas command, including any options to save the figure in a different format. The more restricted hgexport command, which saves figures to either bitmap or metafile files, depending on the rendering method in effect, is also available.
See Exporting the Graph for an example.
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 supports a variety of data file formats, including MATLAB data files, which have a .mat extension.
You can generate MATLAB code that recreates a figure and the graph it contains by selecting Generate M-File from the figure File menu. This option is particularly useful if you have developed a graph using plotting tools and want to create a similar graph using the same or different data.
Create backward-compatible FIG-files by following these two steps:
Ensure that any plotting functions used to create the contents of the figure are called with the 'v6' argument, where applicable.
Use the '-v6' option with the hgsave command.
Note The v6 option enables users of Version 7.x of MATLAB to create FIG-files that previous versions can open. It is obsolete and will be removed in a future version of MATLAB. For more information, see Plot Objects and Backward Compatibility in the MATLAB Graphics documentation. |
![]() | Preparing Graphs for Presentation | Creating Mesh and Surface Plots | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |