Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar...

15
MATLAB WORKSHOP www.jugaruinfo.com Specialized Plots Mr.Amit Kumar jugaruinfo.com Back to contents

Transcript of Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar...

Page 1: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Specialized Plots

Mr.Amit Kumar jugaruinfo.com

Back to contents

Page 2: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Introduction MATLAB supports a variety of graph types that enable you to present information effectively. The type of graph you select depends, to a large extent, on the nature of your data. The following list can help you select the appropriate graph:

• Bar and area graphs are useful to view results over time, comparing results, and displaying individual contribution

to a total amount.

• Pie charts show individual contribution to a total amount. • Histograms show the distribution of data values. • Stem and stairstep plots display discrete data. • Compass, feather, and quiver plots display direction and velocity vectors. • Contour plots show equivalued regions in data. • Interactive plotting enable you to select data points to plot with the pointer. • Animations add an addition data dimension by sequencing plots.

Bar and Area Graphs Bar and area graphs display vector or matrix data. These types of graphs are useful for viewing results over a period

of time, comparing results from different datasets, and showing how individual elements contribute to an aggregate

amount. Bar graphs are suitable for displaying discrete data, whereas area graphs are more suitable for displaying

continuous data.

Function Description

bar Displays columns of m-by-n matrix as m groups of n vertical

bars

barh Displays columns of m-by-n matrix as m groups of n horizontal bars

bar3 Displays columns of m-by-n matrix as m groups of n vertical 3- D bars

bar3h Displays columns of m-by-n matrix as m groups of n horizontal 3-D bars

area Displays vector data as stacked area plots

Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions display 2- and 3-D bar graphs,

and vertical and horizontal bar graphs.

Two-Dimensional Three-Dimensional

Vertical bar bar3

Horizontal barh bar3h

Grouped Bar Graph By default, a bar graph represents each element in a matrix as one bar. Bars in a 2-D bar graph, created by the bar

function, are distributed along the x-axis with each element in a column drawn at a different location. All elements in a

row are clustered around the same location on the x-axis.

Back to contents

33

Page 3: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

For example, define Y as a simple matrix and issue the bar statement in its simplest form. Y = [5 2 1;8 7 3;9 8 6;5 5 5;4 3 2]; bar(Y) The bars are clustered together by rows and evenly distributed along the x-axis.

The first cluster of bars represents

the first row in Y. Y(1,:) = [5 2 1]

The bar3 function, in its simplest form, draws each element as a separate 3-D block, with the elements of each column

distributed along the y-axis. Bars that represent elements in the first column of the matrix are centered at 1 along the x-

axis. Bars that represent elements in the last column of the matrix are centered at size(Y,2) along the x-axis. For example,

bar3(Y) displays five groups of three bars along the y-axis. Notice that larger bars obscure Y(1,2) and Y(1,3). By default, bar3 draws detached bars. The statement bar3(Y,'detach') has the same effect. Labeling the Graph. To add axes labels and x tick marks to this bar graph, use the statements xlabel('X Axis') ylabel('Y Axis') zlabel('Z Axis')

Back to contents

34

Page 4: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Grouped 3-D Bars Cluster the bars from each row beside each other by specifying the argument 'group'. For example, bar3(Y,'group') groups the bars according to row and distributes the clusters evenly along the y-axis.

Page 5: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Horizontal Bar Graphs For horizontal bar graphs, the length of each bar equals the sum of the elements in the row. The length of each segment

is equal to the value of its respective element. barh(Y,'stack') grid on set(gca,'Layer','top') % Display gridlines on top of graph

Area Graphs Showing Contributing Amounts Area graphs are useful for showing how elements in a vector or matrix contribute to the sum of all elements at a particular

x location. By default, area accumulates all values from each row in a matrix and creates a curve from those values. Using this matrix, Y = [5 1 2;8 3 7;9 6 8;5 5 5;4 2 3]; the statement, area(Y)

displays a graph containing three area graphs, one per column. The height of the area graph is the sum of the elements in

each row. Each successive curve uses the preceding curve as its base.

Back to contents

Page 6: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Pie Charts

Pie charts display the percentage that each element in a vector or matrix contributes to the sum of all elements. pie and

pie3 create 2-D and 3-D pie charts. Example – Pie Chart Here is an example using the pie function to visualize the world population by continents. cont=char('Asia','Europe','Africa','N.America',...

'S.America'); pop=[3332;696;694;437;307]; pie(pop) for i=1:5

gtext(cont(i,:)); end title('World Population','fontsize',18)

Back to contents

Page 7: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Histograms MATLAB’s histogram functions show the distribution of data values. The functions that create histograms are hist and rose. hist - Displays data in a Cartesian coordinate system rose -Displays data in a polar coordinate system The histogram functions count the number of elements within a range and display each range as a rectangular bin. The

height (or length when using rose) of the bins represents the number of values that fall within each range.

Histograms in Cartesian Coordinate Systems The hist function shows the distribution of the elements in Y as a

histogram with equally spaced bins between the minimum and

maximum values in Y. If Y is a vector and is the only argument,

hist creates up to 10 bins. For example, yn = randn(10000,1); hist(yn) generates 10,000 random numbers and creates a histogram with

10 bins distributed along the x-axis between the minimum and

maximum values of yn.

Histograms in Polar Coordinate Systems A rose plot is a histogram created in a polar coordinate system.

For example, consider samples of the wind direction taken over

a 12-hour period. wdir = [45 90 90 45 360 335 360 270 335 270 335 335]; To display this data using the rose function, convert the data to

radians; then use the data as an argument to the rose function.

Increase the LineWidth property of the line to improve the

visibility of the plot (findobj). wdir = wdir * pi/180; rose(wdir) hline = findobj(gca,'Type','line');

set(hline,'LineWidth',1.5) The plot shows that the wind direction was primarily 335° during

the 12-hour period.

Back to contents

Page 8: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Discrete Data Graphs MATLAB has a number of specialized functions that are appropriate for displaying discrete data. This section describes

how to use stem plots and stairstep plots to display this type of data. (Bar charts, discussed earlier in this section, are also

suitable for displaying discrete data.)

Discrete Data Plotting Commands stem - Displays a discrete sequence of y-data as stems from x-

axis stem3 - Displays a discrete sequence of z-data as stems from

xy-plane stairs -Displays a discrete sequence of y-data as steps from x-

axis

Two–Dimensional Stem Plots A stem plot displays data as lines (stems) terminated with a marker symbol at each data value. In a 2-D graph, stems extend from the x-axis.The stem function displays two-dimensional discrete sequence data. For example, t=linspace(0,2*pi,50); f=exp(-.2*t).*sin(t); stem(t,f) title('Two Dimensional Stem Plot',...

'fontsize',18,'color','red')

Three-Dimensional Stem Plots stem3 displays 3-D stem plots extending from the xy-plane.

With only one vector argument, MATLAB plots the stems in one row at x = 1 or y = 1, depending on whether the argument is a column or row vector. stem3 is intended to display data that you cannot visualize in a 2-D view. For example, t=linspace(0,6*pi,150); x=t; y=t.*sin(t); z=exp(t/10)-1; stem3(x,y,z) xlabel('t','fontsize',14,'color','blue') ylabel('tsin(t)','fontsize',14,'color','blue') zlabel('e^(t/10)-1','fontsize',14,'color','blue') title('Three Dimensional Stem Plot',...

'fontsize',18,'color','red')

Back to contents

39

Page 9: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Stairstep Plots Stairstep plots display data as the leading edges of a constant interval (i.e.,zero-order hold state). This type of

plot holds the data at a constant y-value for all values

between x(i) and x(i+1), where i is the index into the x

data. This type of plot is useful for drawing time-history

plots of digitally sampled data systems. For example, define a function f that varies over time, alpha = 0.01; beta = 0.5; t = 0:10; f = exp(-alpha*t).*sin(beta*t);

stairs(t,f) hold on

plot(t,f,'--*')

hold off label = 'Stairstep plot of e^{–(\alpha*t)} sin\beta*t';

text(0.5,–0.2,label,'FontSize',14,’color’,’red’) xlabel('t

= 0:10','FontSize',14) axis([0 10 –1.2 1.2])

Direction and Velocity Vector Graphs Several MATLAB functions display data consisting of direction vectors and velocity vectors. This section describes these

functions. You can define the vectors using one or two arguments. The arguments specify the x and y components of the vectors relative to the origin. If you specify two arguments, the first specifies the x components of the vectors and the

second the y components of the vectors. If you specify one argument, the functions treat the elements as complex

numbers. The real parts are the x components and the imaginary parts are the y components.

Vector Plotting Commands compass- Displays vectors emanating from the origin of a polar plot. quiver-Displays 2-D vectors specified by (u,v) components. quiver3- Displays 3-D vectors specified by (u,v,w) components.

Compass Plots The compass function shows vectors emanating from the origin of a graph. The function takes Cartesian coordinates and plots them on a circular grid. th=-pi:pi/5:pi; zx=cos(th); zy=sin(th); z=zx+i*zy; compass(z) gtext('z=cos(\theta)+isin(\theta)','fontsize',18,'color','r ed') title('compass plot','fontsize',18,'color','red')

Back to contents

40

Page 10: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Two-Dimensional Quiver Plots The quiver function shows vectors at given points in two-dimensional space. The vectors are defined by x and y components. For example: r=-2:.2:2; [x,y]=meshgrid(r,r); z=x.^2-5*sin(x.*y)+y.^2; [dx,dy]=gradient(z,.2,.2); quiver(x,y,dx,dy); title('quiver plot','fontsize',18,'color','red')

Three-Dimensional Quiver Plots Three-dimensional quiver plots (quiver3) display

vectors consisting of (u,v,w) components at (x,y,z)

locations. For example, you can show the path of a

projectile as a function of time,

v(z)=vzt+at2/2 First, assign values to the constants vz and

a. vz = 10; % Velocity a = –32; % Acceleration Then, calculate the height z, as time varies from 0 to 1 in increments of 0.1. t = 0:.1:1; z = vz*t + 1/2*a*t.^2; Calculate the position in the x and y directions. vx = 2; x = vx*t; vy = 3; y = vy*t; Compute the components of the velocity vectors . u = gradient(x); v = gradient(y); w = gradient(z); scale = 0; quiver3(x,y,z,u,v,w,scale) view([70 18])

Back to contents

41

Page 11: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Contour Plots Creating Simple Contour Plots contour and contour3 display 2-D and 3-D contours, respectively. They require only one input argument — a matrix interpreted as heights with respect to a plane. In this case, the contour functions determine the number of contours to display based on the minimum and maximum data values. To explicitly set the number of contour levels displayed by the functions, you specify a second optional argument.

Contour Plot of the Peaks Function

The statements

[X,Y,Z] = peaks; contour(X,Y,Z,20) title('Twenty Contours of the peaks Function') display 20 contours of the peaks function in a 3-

D view and increase the line width to 2 points.

Interactive Plotting

The ginput function enables you to use the mouse or the arrow keys to select points to plot. ginput returns the coordinates of the pointer's position, either the current position or the position when a mouse button or key is pressed. See the ginput function for more information. Example -- Selecting Plotting Points from the Screen This example illustrates the use of ginput with the spline function to create a curve by interpolating in two dimensions.

First, select a sequence of points, [x,y], in the plane with ginput. Then pass two one-dimensional splines through the

points, evaluating them with a spacing one-tenth of the original spacing. axis([0 10 0 10]) hold on % Initially, the list of points is empty.

xy = [ ];

n = 0; % Loop, picking up the points.

disp('Left mouse button picks points.') Back to contents

Page 12: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

disp('Right mouse button picks last point.') but = 1; while but == 1

[xi,yi,but] = ginput(1); plot(xi,yi,'ro') n = n+1; xy(:,n) = [xi;yi];

end % Interpolate with a spline curve and finer

spacing. t = 1:n;

ts = 1: 0.1: n; xys = spline(t,xy,ts); % Plot the interpolated curve.

plot(xys(1,:),xys(2,:),'b-');

hold off This plot shows some typical output.

Back to contents

43

Page 13: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Animation We all know the visual impact of animation. If you have a lot of data representing a function or a system at several time

sequence, you may wish to take advantages of MATLAB’s capability to animate your data. There are three types of

facilities for animation in MATLAB 1. Comet plot: This is the simplest and the most restricted facility to display a 2-D or 3-D

line graph as an animated plot. The command comet(x,y) plots the data in vectors x and

y with a comet moving through the data points. The trail of the comet traces a line

connecting through the data points. So rather than having the entire plot appear on the

screen at once, you can see the graph ‘being plotted’. 2. Movies: If you have a sequence of plots that you would like to animate, use the built-in

movie facility. The basic idea is to store each figure as a frame of the movie , with each

frame stored as a column vector of a big matrix, say M and then to play the frames on the

screen with command movie(M). 3. Handle Graphics: Another way, and perhaps the most versatile way, of creating

animation is to use Handle Graphics facilities. There are two important things to know to be able to create animation using Handle Graphics:

• The command drawnow which flushes the graphics output to the screen without

waiting for the control to return to MATLAB. • The object property erasemode which can be set to normal, background, none,

xor to control the appearance of the object when graphics screen is redrawn. Examples:

t=0:.01:100; y=t.*sin(t); comet(t,y)

(It’s better to see it

on the screen)

Back to contents

44

Page 14: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions

MATLAB WORKSHOP

www.jugaruinfo.com

Brownian motion % First, decide on the number of frames:

nframes = 50; % Next, set up the first plot as before, except

using the default EraseMode (normal):

x = rand(n,1)-0.5; y = rand(n,1)-

0.5; h = plot(x,y,'.');

set(h,'MarkerSize',18,'color','red');

axis([-1 1 -1 1])

axis square

grid off %Generate the movie and use getframe to

capture each frame:

for k = 1:nframes x = x + s*randn(n,1); y = y + s*randn(n,1); set(h,'XData',x,'YData',y) M(k) = getframe;

end %Finally, play the movie 5 times: movie(M,5) (It’s better to see it on the screen)

The bead going around a circular path

leaves its tail: th=linspace(0,2*pi,1000);

x=cos(th);y=sin(th);

h=line(x(1),y(1),'marker','o',... 'markersize',18,'erase','xor');

h1=line(x(1),y(1),'marker','o',... 'markersize',18,'erase','none');

axis([-2 2 -2 2]);axis('square');

for k=2:length(th) set(h,'xdata',x(k),'ydata',y(k));

set(h1,'xdata',x(k),'ydata',y(k));

drawnow end

(It’s better to see it on the screen)

Back to contents

Page 15: Specialized Plots - Jugaruinfo · area Displays vector data as stacked area plots Types of Bar Graphs MATLAB has four specialized functions that display bar graphs. These functions