Sunteți pe pagina 1din 26

PLOTTING IN TWO

DIMENSIONS
Elementary 2-D Plots
The most basic, yet often the most useful, graph that you may wish to create is a simple line plot
of numeric data. MATLAB provides a set of high-level commands that are used to create these
simple line plots.

The following objects and terms are occasionally referred to in this section:

 figure: the window in which other graphics objects are placed


 axes: a graphics object that defines a region of the figure in which the graph is drawn
 line: a graphics object that represents the data that you have plotted
 text: a graphics object that is comprised of a string of characters and terms
 title: the text object that is located directly above an axes object
 xlabel: the text object associated with the x-axis
 ylabel: the text object associated with the y-axis
A General Overview of the Plot Command

Most of the MATLAB graphics commands are straightforward and intuitive. The plot command
is the first one that we will explore. For example, a graph of an arbitrary set of data values
assigned to the variable y can be generated using the command plot(y). A data set was the cubic
of the numbers from negative five to four in step increments of one tenth. This data can be
generated and plotted by typing:

y = (-5:0.1:4).^3;
plot(y);

Notice that the x-axis labels are not the numbers that were cubed; rather they are the subscript or
index numbers of the vector y. MATLAB automatically plots your data versus the index number
when only one argument is passed to the plot function. You can verify this by typing length(y)
and seeing that ans = 91 is returned. In the figure, you can see that the last point defining the line
(in the upper right-hand corner) is at the point 91 on the x-axis and 64 = y (91) on the y-axis.

Although there may be instances in which having the indices of the plotted data displayed along
the x-axis is useful, in many cases it will be more informative to display the value of the input or
parameter that was responsible for the data output. In order to accomplish this for our previous
example, we can use:

x = -5:0.1:4;
y = (x).^3;
plot (x, y);
Now we can add some labels to the x- and y-axes, a title to make the graph more informative,
and a grid to assist in estimating values from the line in the graph. We will create the label “x”
for the x-axis, “y” for the y-axis, and put “Graph of y = x^3” as the title to the graph. MATLAB
makes adding these very simple; just type the following at the command prompt:

xlabel('x');
ylabel('y');
title('Graph of y = x^3');
grid;

The plot command arguments are not restricted to being vectors; the inputs may also be
matrices. When passing inputs to the plotting function, there are several simple rules to keep in
mind so that the appearance of the graph is what you expect. The rules can be summarized as
follows:

 plot(y)

o If y is a vector, you will generate a line of y versus the index numbers of y.


o If y is a matrix, you will generate a set of lines where each line corresponds to the
graph of one of the matrix columns versus the row number.

 plot(x,y)

o If x and y are vectors of the same length, a graph of y versus x will be displayed.
o If x is a vector and y is a matrix, the rows or columns of y will be plotted against
x. If a column of the y matrix has the same length as vector x, then the columns
will be plotted versus x. If the rows have the same length as vector x, then the
rows will be plotted versus x. If the number of rows and columns of y are the
same, the columns will be plotted versus x.
o If x is a matrix and y is a vector, y will be plotted against either the rows or
columns of x. If a column of the x matrix has the same length as vector y, then y
will be plotted versus columns of x. If the number of rows of x is equivalent to the
length as vector y, then y will be plotted versus the rows of x.
o If the number of rows and columns of x are the same, y will be plotted versus the
columns of x.
o If x and y are matrices which have the same number of rows and columns, the
columns of y will be plotted against the columns of x.

x = (0:0.2:9)';
alpha = 0:5;
y = besselj(alpha,x); % Bessel function
plot(x,y)
xlabel('x');
ylabel('y');
title('y = besselj(ALPHA,x), for alpha = 0,1,2,3,4, and 5');
The y variable is a 46-by-6 element matrix and x is a vector with 46 elements. For this example it
does not matter to the plot command if y is transposed or not; MATLAB recognizes the size of
the two input variables and appropriately plots y in the orientation that matches the dimensions
of x. However, the besselj function does require that alpha have as many columns as rows in x.

Colors, Line Style and Marker Style


x1 = [-3:.2:3];
y1 = x1.^2 + randn(size(x1));
p = polyfit(x1,y1,2);
x2 = [-3:.5:3];
y2 = polyval(p,x2);
plot(x1,y1,'og',x2,y2,'--c');
xlabel('Input');
ylabel('Output');
title('Noisy data = "o" and Fitted Curve = "--" ');
grid
Generating Plots with Multiple Data Sets

Plot multiple sets of data with a single plot command is possible. However, MATLAB does not
restrict you to using a single call to the plot command in order to plot multiple lines in a graph.
A command which you might find very useful is the hold command. The hold command allows
you to add additional lines to the current graph without erasing what already exists in it. When
hold is not used, the plot command will replace the contents of the current graph. The hold
command can be used in three different ways:

Hold on tells MATLAB that you want all subsequent lines and surfaces to be added to the
current graph.

Hold off is used to turn off the hold command, setting MATLAB back to the default mode of
replacing the current graph with a new one.

Hold when used by itself will toggle the mode between the hold on and hold off state.

x = -2:.1:2;
plot(x,sin(x),'-r');
hold on
plot(x,sin(x.^2),'--b');
plot(x,cos(x.^2),':g');
hold off
In some instances you will have data sets that you want to display on the same graph; however,
the y-axis data values are not in the same range. MATLAB provides a useful graphics function
for just such an occasion. The command plotyy, will help you plot these types of data sets on the
same graph.

x1 = 0:.1:20;
y1 = x1.*sin(x1);
x2 = 10:.2:25;
y2 = 50*x2;

plot(x1,y1,'-b',x2,y2,'--g');
title('y1 is the blue line, y2 is the green dashed line');
ylabel('y');
xlabel('x');

Instead we could use plotyy to plot the data:

plotyy(x1,y1,x2,y2)
To label the axes use the following codes:

[axeshandles,line1handle,line2handle]=plotyy(x1,y1,x2,y2);
set(line1handle,'linestyle','-','color','blue');
set(line2handle,'linestyle','--','color','green');
title('y1 is the blue line,y2 is the green dashed line');
axes(axeshandles(1));
ylabel('y1=x.*sin(x)');
axes(axeshandles(2));
ylabel('y2=50*x');
xlabel('x')
axis([xmin xmax ymin ymax]) Set the minimum and maximum x- and y-axis
limits. xmax and/or ymax can be set to Inf to
force MATLAB to autoscale the upper x- and
y-axis limits. xmin and/or ymin can be set to -
Inf to force MATLAB to scale the lower x and
y-axis limits.

axis auto Returns the axis scaling to its default,


automatic mode where, for each dimension,
'nice' limits are chosen based on the extents of
all lines in the graph
axis manual Freezes the scaling at the current limits, so that
if hold is turned on, subsequent plots will use
the same limits
axis normal puts the axes into the default (automatic) state
and restores the current axis box to full size,
removing any restrictions on the scaling of the
units. This undoes the effects of axis square,
and axis equal.
axis square Forces the axes to have square dimensions.
axis equal Forces the unit spacing, i.e., the tic marks, on
the x- and y- axis to be equal.
axis ij Puts origin of graph in upper-left corner. The
x-axis scale numbering increases from left to
right. The y-axis scale numbering increases
from top to bottom.
axis xy Forces the axes to use a standard Cartesian
coordinate system with the origin of the graph
in the lower-left corner. The x-axis scale
numbering increases from left to right.
The y-axis scale numbering increases from
bottom to top.
axis tight Forces the x- and y-axes limits to the minimum
and maximum data values, i.e., the range of the
data.
axis off Turns off, i.e., hides, the axes labels, tic marks,
and box by making them invisible.
axis on Turns on, i.e., makes visible, the axes labels,
tic marks, and box.
Creating Supporting Text and Legends

The text function is both a high- and low-level graphics function that can be used to add
character strings to a graph. The most elementary way that text can be added to the current graph
is with text(x,y,'text') where the data point (x,y) corresponds to a location in the current axes.

% Create and plot the x and y data


x = -2:0.1:2;
y = 3 - (x+1).^2;
plot(x,y);
xlabel('x'); ylabel('y'); title('y = 3 - (x+1).^2');
grid on
axis([-2 2 -5 5]);
% Determine the maximum y data value
[max_y_value,max_y_index] = max(y);
corresponding_x_value = x(max_y_index);
% Put a red circle symbol at the maximum data point
hold on
plot(corresponding_x_value,max_y_value,'or');
hold off
% Create a string vector
our_string = sprintf('%g is the maximum data point',...
max_y_value);
% Put the string into the graph at the max y value
text(corresponding_x_value,max_y_value+0.5,our_string);
The text function can also be used in a manner very similar to the way plot is used. For instance,
if you want to create a scatter plot of the percent change in the consumer price index versus
unemployment between 1965 and 1980, you can type

% Source of data: Economic Report of the President, 1986.


cpi_data = [1.7 2.9 2.9 4.2 5.4 5.9 4.3 3.3 6.2 ...
11.0 9.1 5.8 6.5 7.7 11.3 13.5];
perc_unemploy_data = [4.5 3.8 3.8 3.6 3.5 4.9 5.9 ...
5.6 4.9 5.6 8.5 7.7 7.0 6.0 5.8 7.0];
year_strings = ['1965';'1966';'1967';'1968';'1969';...
'1970';'1971';'1972';'1973';'1974';...
'1975';'1976';'1977';'1978';'1979';'1980' ];
plot(perc_unemploy_data,cpi_data,'o');
% In this next text command two text properties were made
% use of so that the plot would look better. You will
%learn how to manipulate these in Chapter 7.
text(perc_unemploy_data,cpi_data,year_strings,...
'fontsize',10,...
'verticalalignment','bottom');
axis([0 10 0 14]);
xlabel('Percent Unemployment');
ylabel('Percent change in CPI');
The legend function creates a legend of the line types that you have used in the current graph and
associates these line types with the text strings that you pass to it. The order in which the lines
are created is the order in which they are associated with the legend strings.

x = 0:.1:(2*pi);
sx=sin(x);
cx=cos(x);
plot(x,sx,'-r',x,cx,'--c');
axis([0 2*pi -1.5 1.5])
legend('Sin(x)','Cos(x)');

If you are not sure in which order the lines were created or you want only a few of the lines put
into a legend you can use this form of the legend function:

legend(linetype1, string1,linetype2,string2,...)

This is probably the safest way to insure that when you create the legend the text string is
correctly associated with the line you wanted. Implementing this for the previous example, we
see that the legend command is replaced with

legend('-r','Sin(x)','--c','Cos(x)');

If you do not like the position that was automatically chosen by the legend function, you can use
the mouse to click and drag the legend to a location of your choice.
Using Subplot to Create Multiple Axes

You’ve seen that you can have multiple plots on an axis, either by plotting multiples or by using
the hold command and issuing another plot command. However, you are not limited to having
one axes object in a Figure Window. The easiest way to create multiple axes in a Figure Window
is to make use of the command subplot. This function breaks up the Figure Window's space into
subregions or panes and is very useful for showing related information that is better viewed in
individual plots. Calling the command with three marguments creates these subregions; the first
two specify how many regions there will be in terms of rows and columns, and the third
argument specifies which region you wish to plot in. For example, subplot(m,n,p) subdivides the
Figure Window into m-by-n regions and creates axes in the pth region, where regions are
numbered from left to right and top to bottom within the figure. For example, the following will
break up the Figure Window into three distinct regions and create an axes object in the second
one.

subplot(3,1,2)

After you have created an axes object in one of the regions, you can then use any plotting
command you want. The axes created with subplot can be treated in the same way as the ones
that are created when no subregions are specified. In fact, you can create an axes object which
encompasses the entire Figure Window's space by issuing subplot(1,1,1) and get the same axes
that you would have gotten by using plot commands without the subplot function.

% CREATE THE X and Y SHAPE DATA.


x_square = [-3 3 3 -3 -3];
y_square = [-3 -3 3 3 -3];
x_circle = 3*cos([0:10:360]*pi/180);
y_circle = 3*sin([0:10:360]*pi/180);
x_triangle = 3*cos([90 210 330 90]*pi/180);
y_triangle = 3*sin([90 210 330 90]*pi/180);
%PLOT THE CIRCLE IN THE UPPER LEFT SUBREGION.
subplot(2,2,1)
plot(x_circle,y_circle,'--g'); axis([-4 4 -4 4]);
axis('equal');
title('Circle');
%PLOT THE SQUARE IN THE UPPER RIGHT SUBREGION.
subplot(2,2,2)
plot(x_square,y_square,'-r'); axis([-4 4 -4 4]);
axis('equal');
title('Square');
%PLOT THE TRIANGLE IN THE LOWER LEFT SUBREGION.
subplot(2,2,3)
plot(x_triangle,y_triangle,':b'); axis([-4 4 -4 4]);
axis('equal');
title('Triangle');
%PLOT THE COMBINATION PLOT IN THE LOWER RIGHT SUBREGION.
subplot(2,2,4)
plot(x_square,y_square,'-r');
hold on;
plot(x_circle,y_circle,'--g');
plot(x_triangle,y_triangle,':b');
axis([-4 4 -4 4]); axis('equal');
title('Combination Plot');

A useful (and undocumented) manipulation of the subplot can be used to place a different
number of subplots on a row. For instance, instead of having four subplots in a two-by-two
matrix, we could have two subplots on the top row and one subplot on the bottom row that spans
the figure.
subplot(2,2,1),ezplot('sin(x)')
subplot(2,2,2),ezplot('cos(x)')
subplot(2,1,2),ezplot('sin(x)^2/x^2')

subplot(2,2,2),ezplot('sin(x)')
subplot(2,2,4),ezplot('cos(x)')
subplot(1,2,1),ezplot('sin(x)^2/x^2')
Bar Graphs

A bar graph can quickly be created with the bar command. The bar function can be used to plot
bars with heights specified by the variable argument, bar_height_vector, versus the index number
of that variable by using

bar(bar_height_vector);

If instead of the index to the variable, you want to plot bars versus another variable, you can use
bar(x,y), where x and y are equal length vectors, and vector x contains values which are both in
ascending order and evenly spaced. If x is not evenly spaced or in ascending order, the routine
will do the best it can do, but the results will most likely not be what you wanted. If, for example,
you want to create a bar graph of the percentage of widgets that passed quality tests versus the
assembly line number, you can type

assembly_line_number = [1 2 3 4 5 6 7];
percentage_passed = [85 93 87 91 95 71 98];
bar(assembly_line_number,percentage_passed);
xlabel('Assembly Line Number')
ylabel('Percentage Passed')
When you plot bar graphs, you may wish to have labels other than the numeric ones that
automatically appear on your x-axis. In these cases, the simplest way to plot your bar graph is
with the bar(bar_height_vector) format.

You also have the option of passing a string argument to define the color and line style of the
bars with

bar(x,line_style_string);

or

bar(x,y,line_style_string);

The string, line_style_string, takes on the same format as the string used in the plot command.
The bar function can also be used to create the data which defines the lines making up the bars.
This is done by requesting that the bar function return two output variables with either

[x_line_data,y_line_data] = bar(x);

or

[x_line_data,y_line_data] = bar(x,y);

In this mode of operation, the bar function does not draw anything. However, these output
variables, x_line_data and y_line_data, can be used with the plot command (e.g.,
plot(x_line_data,y_line_data)) to generate the bar graph.

The bar plotting function has the ability of clustering multiple data sets, stacking and generating
horizontal bar plots. When you pass a matrix to the bar function, a bar will be generated for each
element of the matrix. The bars associated with the elements in a specific row will be clustered
together, while at the same time maintaining color properties for the bars generated from the
matrix elements in a specific column. For example, if we have a 2-by-4 matrix, there will be 4
groups of 2 bars clustered around each x-axis data point associated with a row element in the
matrix

x = [1 3 4 6];
Y = [ 3 1 ; 4 2 ; 2 3 ; 2.5 2];
bar(x,Y);
grid on;
subplot(221);
bar(Y,'stack');
subplot(222);
bar(x,Y,.5) % The 0.5 specifies that the grouped bars be
% separated by more than the default of 0.8.
subplot(223);
barh(Y,'stack');
subplot(224);
barh(Y,1); % The 1 specifies that the bars in a group
% touch one another
The examples done here can be repeated using MATLAB’s bar3 and bar3h commands to give
the plots a 3-D look. Just repeat the examples and substitute bar3 for bar and bar3h for barh.
The only other thing you have to know is that the default style for 2-D bar graphs is grouped
while the default style for 3-D bar graphs is 'detached'. Therefore, when the style is not explicitly
stated in the example, you will have to provide the 'grouped' style to get the 3-D counterpart.

bar3(x,Y,'grouped');

Histograms

The MATLAB hist function can be used to automatically create a histogram of the data you pass
to it. If you use hist(y), the function will create a histogram with 10 equally spaced bins that
cover the range of values between the minimum and maximum values of the variable y. In
addition, you may specify either the number of bins or the centers of the bins by respectively
passing a scalar or vector as a second argument to the hist function. The hist function makes use
of the bar function to plot the histogram, and therefore, when you pass bin centers as a vector
argument, you should pass points that are equally spaced and in ascending order. If the centers
are not equally spaced or in order, you may not get the results you expect. Just as with the bar
function, you may suppress the plotting of the histogram by having the function return two
output variables.
[n,x] = hist(y);

or

[n,x] = hist(y,number_of_bins);

or

[n,x] = hist(y,bin_centers);

number_data_points = 5000;
Beta = 2;
y = -Beta*log(rand(1,number_data_points));
x = 0.2:0.4:10; % Bin Centers
hist(y,x);
ylabel('Count')
To plot the percentage of data points that falls within a particular bin on the yaxis instead of the
count, we could use

[n,centers] = hist(y,x);
bar(centers,(n/number_data_points)*100);
ylabel('Percentage');
Stem Plots

Stem plots provide yet another method of visualizing discrete data sequences, such as sampled
time series data. In these types of graphs, vertical lines terminating with a symbol such as a circle
are drawn from the zero value point on the y-axis to the values of the elements in the vector
passed along with the command, stem(y). If you want spacing other than that provided by the
element index number, you can use stem(x,y), where x specifies where the line is drawn along
the x-axis.

x = 0:0.25:(3*pi);
stem(x,sin(x));
title('stem(x,sin(x))');
xlabel('x');
Plots with Error Bars

Error bars are used to show uncertainty in the accuracy of plotted values. With the
errorbar(x,y,e) function, MATLAB will plot a line which passes through the set of (x,y) points
with vertical lines that are called error bars centered about the (x,y) points that have lengths
corresponding to twice the elements of the error vector e. When x, y, and e are same sized
matrices lines with their error bars will be drawn on a per column basis. This type of plot can be
useful if you are plotting data mean values, yet you wish to convey the range over which values
may have fallen.

x_values = 1:0.5:10;
y_mean_values = 10*exp(-x_values)+3;
y_std_deviation_values = 1./x_values;
errorbar(x_values,y_mean_values,3*y_std_deviation_values)
;
xlabel('x'); ylabel('y');
title('Plot of data means, with errorbars indicating +/-3
standard deviations');
Pie Charts

In MATLAB pie charts display the percentage that each element in a vector or matrix contributes
to the sum of all elements. They are useful when you want to show the relative proportion of data
elements to one another. For example, let’s say you have some data representing where
government revenues come from, specifically Soc.Sec. Tax = 31%, Personal Income Tax = 36%,
Borrowing = 18%, Corporate Taxes = 8%, Misc. = 7%.

gov_rev_percentages = [31 36 18 8 7];


h = pie(gov_rev_percentages);
explode = [0 0 0.25 0 0];
h = pie(gov_rev_percentages,explode);
pielabel(h,{'Soc. Sec. Tax: ';'Personal Income Tax: ';...
'Borrowing: ';'Corporate Taxes: ';'Misc: '});

Just like the 3-D looking bar chart we saw earlier, MATLAB provided a 3-D looking pie chart function
called pie3. The pie3 function is used in exactly the same manner as the pie function.

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