Plots

Plotting Data

We explore now the basic functions of graphics in MATLAB.

Support Functions

These four are the most important, there are many more.

  • legend,labels the various elements on a graph, legend(’Series 1’,’Series 2’).
  • title,title of graph, title (’Figure Title’).
  • xlabel, ylabel and zlabel produce text labels on the x, y and if present z axes respectively, standard
    usage is xlabel(’X Data Name’).
  • axis, axis can be used to both get the axis limits and set the axis limits.
    1. To retrieve the current axis limits, enter AX = axis();. AX will be a row vector of the form [xlow xhigh ylow yhigh (zlow) (zhigh)] where zlow and zhigh are only included if the figure is 3D.
    2. The axis can be changed by calling axis([xlow xhigh ylow yhigh (zlow) (zhigh)]) where the z-variables are only allowed if the figure is 3D.
    3. axis can also be used to tighten the axes to include only the minimum space required to express the data using the command axis tight.

Plot

plot is the basic plotting command.

plot(x1,y1,format1,x2,y2,format2,…)

where xi and yi are vector of the same size and format i is a format string of the form color shape linespec.

  • color can be any of b blue, g green, r red, c cyan, m magenta, y yellow, k black.
  • shape can be any of o circle, x x-mark, + plus, * star, s square, d diamond, v triangle (down), ^ triangle (up), < triangle (left), > triangle (right), p pentagram, h hexagram.
  • linespec can be any of solid, : dotted, -. dashdot, – – dashed, (non) no line.

We can combine this three to form a format string, for instance:

  • ’gs-’, will produce a green solid line with squares at every data point,
  • ’r+ ’, will produce a set of red + symbols at every data point,

Arguments which are not needed can be left out.

  • ’g:’, will produce a green dotted line with no symbol, use the format string.

If not use format string MATLAB will automatically create on.
This is an example,

&gt;&gt; x = linspace(0,1,100);
&gt;&gt; y1 = 1-2*abs(x-0.5);
&gt;&gt; y2 = x;
&gt;&gt; y3 = 1-4*abs(x-0.5).^2;
&gt;&gt; plot(x,y1,'rs:',x,y2,'bo-.',x,y3,'kp- ')

Now we label it,

&gt;&gt; xlabel('x');
&gt;&gt; ylabel('f(x)');
&gt;&gt; title('Plot of three series');
&gt;&gt; legend('f(x)=1-|x-0.5|','f(x)=x','f(x)=1-4*abs(x-0.5).^2');

If we type only plot(y), it will plot the data in vector y against a simple series which labels each observation 1, 2, . . ., length(y).

Plot3

plot3 plots a series against two other series in 3-space.

plot(x1,y1,z1,format1,x2,y2,z2,format2,…)

figure(2)
N=200;
x=linspace(0,8*pi,N);
x=sin(x);
y=linspace(0,8*pi,N);
y=cos(y);
z=linspace(0,1,N);
plot3(x,y,z,'rs:');
xlabel('x');
ylabel('y');
zlabel('z');
title('Spiral');
legend('Spiraling Line')

with “figure(2)” we are creating a new figure graphics object where to plot.

scatter

It produces a scatter plot of the elements of a vector x against the elements of a vector y .
Formatting, such as color or market shape can only be changed by either using handle graphics or manually editing the plot.

figure(4)
x=randn(1000,2);
Sigma=[2 .5;.5 0.5];
x=x*Sigma^(0.5);
scatter(x(:,1),x(:,2),'rs')
xlabel('x')
ylabel('y')
legend('Data point')
title('Scatter plot of correlated normal random variables')

In the next graphics (surf, mesh contour) tools all plot a matrix of z data against vector of x and y data. We will use a bivariate gaussian pdf with mean 0 and covariance [2 .5;.5 .5].

Now we create a pdf values Matrix,

N = 100;
x = linspace(-3,3,N);
y = linspace(-2,2,N);
pdf=zeros(N,N);
for i=1:length(y)
    for j=1:length(x)
        pdf(i,j)=exp(-0.5*[x(j) y(i)]*Sigma^(-1)*[x(j) y(i)]')/sqrt((2*pi)^2*det(Sigma));
    end
end

surf

surf(x,y,pdf)
xlabel('x')
ylabel('y')
zlabel('PDF')
title('Surf of normal PDF')
shading interp

shading interp changes how the colors are applied from a discrete to grid to a continuous grid.

Remarks:

  • The x and y arguments of surf must match the dimensions of the z argument.
  • If [M,N]=size(z), then length(y) must be M and length(x) must be N.
  • This is true of all 3D plotting functions that draw matrix data.
  • In the code above, i is the row iterator which corresponds to y and j is the column iterator, corresponding to x.

mesh

mesh produces a graphic similar to surf but with empty space between grid points. It has the advantage
that the hidden side can be seen, potentially revealing more from a single graphic.

mesh(x,y,pdf)
xlabel('x')
ylabel('y')
zlabel('PDF')
title('Mesh of normal PDF')

contour

Contour is similar to surf and mesh in that it takes three arguments, x, y and z if it differs in that it produces a 2D plot.
contour(x,y,z,N) where N instructs MATLAB how many contours to produce ; if omitted, MATLAB will determine the number of contours based on the variance of the z data.

contour(x,y,pdf);
xlabel('x')
ylabel('y')
title('Contours of normal PDF')

subplot

Subplots allow for multiple plots to be placed in the same figure.
All calls to subplot must specify three arguments, the number of rows, the number of columns, and which cell to place the graphic.

subplot(M,N,#).

where M is the number of rows, N is the number of columns, and # indicates the cell to place the graphic.
For instance, a subplot(3,2,#) the #’s would be refer to

1 2
3 4
5 6

A call to subplot should be immediately followed by some plotting function.

The graphics code in each subplot was taken straight formtheMATLAB help files. The help system
is very comprehensive and illustrates most functions with example code.

subplot(2,2,1);
x = [5 3 0.5 2.5 2];
explode = [0 1 0 0 0];
pie(x,explode)
colormap jet
title('pie function')
axis tight

subplot(2,2,2);
Y = cool(7);
bar3(Y,'detached')
title('Detached')
axis tight

subplot(2,2,3)
bar3(Y,'grouped')
title('bar3')
axis tight

subplot(2,2,4);
x = 1:10;
y = sin(x);
e = std(y)*ones(size(x));
errorbar(x,y,e)
title('errorbar')
axis tight

This is an other one made from us,

r = randn(100,1);
r2 = randn(100,1);

figure(1)
title('Example of two financial series')
subplot(2,2,1);
plot(r);
xlabel('time');
ylabel('Ret');
title('Serie1 returns');
axis tight

subplot(2,2,2);
plot(cumsum([100;r]));
xlabel('time')
ylabel('Price');
title('Serie1 price');
axis tight

subplot(2,2,3);
plot(r2);
xlabel('time');
ylabel('Ret');
title('Serie2 returns');
axis tight

subplot(2,2,4);
plot(cumsum([100;r2]));
xlabel('time')
ylabel('Price');
title('Serie2 price');
axis tight

datetick

datetick(tickaxis) labels the tick lines of an axis using dates, replacing the default numeric labels.
This is an example to convert the x tick labels to month names, keeping the total number of ticks by using the ‘keepticks’ option:

startdate = datenum('01-Jan-2005', 'dd-mmm-yyyy');
enddate = datenum('31-Dec-2010', 'dd-mmm-yyyy');
datevector = linspace(startdate,enddate);
r = randn(length(datevector),1);

plot(datevector,r);
xlabel('time');
ylabel('Ret');
set(gca,'XTick',datevector)
datetick('x','mmm-yy')
title('Serie returns');

Advanced Graphics

Often we want to change our graphics for example the thickness of a line in order to improve its appearance or to add an arrow to highlight a particular feature of a graph.
We can do it in two ways,

  • point-and-click manually editing the plot in the figure window (File–> Edit–>…),
  • handle graphicsprogrammatically change anything about a graph (useful when you have many graphs).

Exportin Plots

On the figure, click File >> Save As >> select the desired format.

Exercises

  1. Using the Price and Returns Matrix saved previously, produce a subplot – with the date – with 4 windows containing:
    1. A scatter plot of one asset that you like and NASDAQ index.
    2. Two histograms of the series
    3. One plot of the two series against the dates. Change the axis labels to text using datetick.
Advertisements
%d bloggers like this: