9. Plots

 

9.1        Deciding to plot data and, for starters, plotting a sine function

9.2        Controlling axes

9.3        Controlling the appearance of plotted points and lines

9.4        Having more than one graph per plot and more types of points and lines

9.5        Getting and setting properties of plotted points

9.6        Adding xlabels, ylabels, and titles

9.7        Adding legends

9.8        Adding text

9.9        Fitting curves

9.10      Creating subplots and turning grids, boxes, and axes on and off

9.11      Exploiting matrix assignments to merge subplots

9.12      Getting and setting properties of axes

9.13      Plotting data points with error bars

9.14      Generating polar plots

9.15      Generating histograms

9.16      Generating bar graphs

9.17      Exporting and printing figures

9.18      Generating other kinds of graphs and getting and setting figure properties

9.19      Practicing plots

 

 

top of page

9.1 Deciding to plot data and, for starters, generating a sine function

 

Code 9.1.1

 

clear all

close all

figure(1)

theta = linspace(0,4*(2*pi),100);

plot(theta,sin(theta));

shg

 

Output 9.1.1

 

 

 

top of page

9.2 Controlling axes

 

Code 9.2.1

 

figure(2)

y = sin(theta);

plot(theta,y);

axis([min(theta) max(theta) min(y) max(y)]);

shg

 

Output 9.2.1

 

 

Code 9.2.2

 

figure(3)

x = theta;

plot(x,y);

x_offset = 1;

y_offset = .2;

xlim([min(x)-x_offset, max(x+x_offset)]);

ylim([min(y)-y_offset, max(y+y_offset)]);

shg

 

Output  9.2.2

 

 

 

top of page

9.3 Controlling the appearance of plotted points and lines

 

 

Code 9.3.1

 

figure(4);

plot(x,y,'g-');

hold on;

plot(x,y,'bo');

shg;

 

Output  9.3.1

 

 

 

top of page

9.4   Having more than one graph per plot and more types of points and lines

 

 

Code 9.4.1

 

figure(5)

plot(x,y,'go-');

y = cos(x);

plot(x,y,'b-s');

shg

 

Output 9.4.1

 

 

 

Code 9.4.2

 

help plot

 

Output 9.4.2

 

Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is a character string made from one element from any or all the following 3 columns:

 

   b     blue     .   point              -     solid

   g     green    o   circle             :     dotted

   r     red      x   x-mark             -.    dashdot

   c     cyan     +   plus               --    dashed  

   m     magenta  *   star              (none)  no line

   y     yellow   s   square

   k     black    d   diamond

                  v   triangle (down)

                  ^   triangle (up)

                  <   triangle (left)

                  >   triangle (right)

                  p   pentagram

                  h   hexagram

                  

For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus at each data point; PLOT(X,Y,'bd') plots blue diamond at each data point but does not draw any line.

 

 

Code 9.4.3

 

figure(6)

plot(x,sin(x),'c+:',x,cos(x),'rd');                               

shg

 

Output 9.4.3:

 

                                                

 

top of page

9.5   Getting and setting properties of plotted points

 

 

Code 9.5.1

 

figure(7)

plot(x,sin(x),'ro-','markersize',12);

xlim([min(x)-x_offset, max(x+x_offset)]);

ylim([min(y)-y_offset, max(y+y_offset)]);

box on

shg

 

Output 9.5.1

 

 

 

Code 9.5.2

 

figure(8)

h = plot(cos(x),sin(x), 'r.','markersize',12);

get(h)

 

Output 9.5.2

 

 

h =

 

                 Color: [1 0 0]

             EraseMode: 'normal'

             LineStyle: '-'

             LineWidth: 0.5000

                Marker: 'o'

            MarkerSize: 12

       MarkerEdgeColor: 'auto'

       MarkerFaceColor: 'none'

                 XData: [1x100 double]

                 YData: [1x100 double]

                 ZData: [1x0 double]

          BeingDeleted: 'off'

         ButtonDownFcn: []

              Children: [0x1 double]

              Clipping: 'on'

             CreateFcn: []

             DeleteFcn: []

            BusyAction: 'queue'

      HandleVisibility: 'on'

               HitTest: 'on'

         Interruptible: 'on'

              Selected: 'off'

    SelectionHighlight: 'on'

                   Tag: ''

                  Type: 'line'

         UIContextMenu: []

              UserData: []

               Visible: 'on'

                Parent: 1.0710e+003

           DisplayName: ''

             XDataMode: 'manual'

           XDataSource: ''

           YDataSource: ''

           ZDataSource: ''

 

 

Code 9.5.3

 

figure(9)

plot(x,y,'g-');

hold on

x_offset = 0;

y_offset = .2;

axis([min(x)-x_offset, max(x)+x_offset, …

      min(y)-y_offset, max(y+y_offset)]);

plot(x,y,'o', ‘color’,’r’,'markersize',6,...

    'markeredgecolor','k','markerfacecolor','r');

 

Output 9.5.3

 

 

 

 

top of page

9.6   Adding xlabels, ylabels, and titles

 

 

Code 9.6.1

 

figure(10)

plot(x,y,'g-');

hold on

x_offset = 0;

y_offset = .2;

axis([min(x)-x_offset, max(x)+x_offset, …
      min(y)-y_offset, max(y+y_offset)]);

plot(x,y,'o','color','r','markersize',6,...

    'markeredgecolor','k','markerfacecolor','r');

xlabel('Time');

ylabel('Happiness');

title('Life has its ups and downs');

 

 

Output 9.6.1

 

 

 

top of page

9.7   Adding legends

 

 

Code 9.7.1

 

figure(11)

max_learn = [10 11 12 13];

trial = [1:10];

c1 = max_learn(1) - exp(-trial);

c2 = max_learn(2) - exp(-trial);

c3 = max_learn(3) - exp(-trial);

c4 = max_learn(4) - exp(-trial);

 

hold on

plot(trial,c4,'g-^');

plot(trial,c3,'m--<');

plot(trial,c2,'b-.>');

plot(trial,c1,'k:v');

legend('Group 4','Group 3',…

       'Group 2','Group 1', …

       'Location','EastOutside');

 

Output 9.7.1

 

 

top of page

9.8   Adding text

 

 

 

Code 9.8.1

 

figure(12)

  

a = 1;           % starting value

b = .5;          % rate parameter

xx = [0:20];

vert_offset = .05;

hor_offset = .50;

 

y_power = a * xx.^-b;

y_exp = a * exp(b*-xx);

 

hold on

box on

plot(y_power,'mo-');

plot(y_exp,'kd-');

 

hor_p = xx(5) + hor_offset;

vert_p = y_power(5) + vert_offset;

text(hor_p,vert_p,'Power function');

 

hor_e = xx(6) + hor_offset;

vert_e = y_exp(6) + vert_offset;

text(hor_e,vert_e,'Exponential function');

 

Output 9.8.1

 

 

 

top of page

9.9   Fitting curves

 

 

Code 9.9.1

 

clear x y

a3 = 0;

a2 = 1;

a1 = 1;

a0 = 0;

x = [-20:20];

randn_coeff = 60;

 

y = a3*x.^3  + a2*x.^2 + a1*x.^1 + a0*x.^0;

r = rand(length(y))*randn_coeff;

r = r(1,:);

y = y + r;

 

fitted_coefficients = polyfit(x,y,1);

y_hat1 = fitted_coefficients(1)*x.^1 + ...

         fitted_coefficients(2)*x.^0; %apply polyfit coefficients to x

 

figure (13)

hold on

plot(y,'bo');         % show original data

plot(y_hat1,'r-');    % show fitted points joined by a line

xlim([0 length(x)]);

box on                % put a box around the graph

c = corrcoef(y, y_hat1);

message = ['Straight line fit: r^2 = ',num2str(c(1,2)^2,3)];

title(message);

 

Output 9.9.1

 

 

 

 

 

Code 9.9.2

 

clear fitted_coefficients;

fitted_coefficients = polyfit(x,y,2);

y_hat2 = fitted_coefficients(1)*x.^2 + ...

         fitted_coefficients(2)*x.^1 + ...

         fitted_coefficients(3)*x.^0;

 

figure (14)

hold on

plot(y,'bo');         % show original data

plot(y_hat2,'r-');    % show fitted points joined by a line

xlim([0 length(x)]);

box on                % put a box around the graph

c = corrcoef(y, y_hat2);

message = ['Quadratic fit: r^2 = ',num2str(c(1,2)^2,3)];

title(message);

 

Output 9.9.2

 

 

 

 

top of page

9.10      Creating subplots and turning grids, boxes, and axes on and off

 

Code 9.10.1

 

figure(15)

 

subplot(4,1,1)

plot(cos(x),'r.','markersize',12);

grid on

 

subplot(4,1,2)

plot(cos(x),'r.','markersize',12);

box on

 

subplot(4,1,3)

plot(cos(x),'r.','markersize',12);

axis off

 

subplot(4,1,4)

plot(cos(x),'r.','markersize',12);

axis square

 

Output 9.10.1

 

  

 

 

top of page

9.11      Exploiting matrix assignments to merge subplots

 

 

Code 9.11.1

 

figure(16)

clear x y

x = [1:10];

y = x + 1;

subplot(4,2,1:2);   % In the 4 rows and 2 columns of subplots,

                    % subplots 1 and 2

xlim([0 1]);

ylim([0 1]);

axis off

text(-.05,.05,'             A Banner Year','fontsize',24);

 

subplot(4,2,3);     % In the 4 rows and 2 columns of subplots,

                    % subplot 3

 

plot(x,y,'k')

text_in_box(.05,.80,'A')

 

subplot(4,2,4);     % In the 4 rows and 2 columns of subplots,

                    % subplot 4

 

plot(x,y,'k')

text_in_box(.05,.80,'B')

 

subplot(4,2,[5 7]); % In the 4 rows and 2 columns of subplots,

                    % subplots 5 and 7

 

plot(x,y,'k')

text_in_box(.05,.90,'C')

 

subplot(4,2,6);     % In the 4 rows and 2 columns of subplots,

                    % subplot 6

 

plot(x,y,'k')

text_in_box(.05,.80,'D')

 

subplot(4,2,8);     % In the 4 rows and 2 columns of subplots,

                    % subplot 8

 

plot(x,y,'k')

text_in_box(.05,.80,'E')

 

Code 9.11.2

 

function text_in_box(x_place,y_place,s)

 

xs = xlim;

ys = ylim;

text(x_place*xs(2),y_place*ys(2),s);

 

 

Output 9.11.1

 

 

 

top of page

9.12      Getting and setting properties of axes

 

Code 9.12.1

 

get(gca)

 

Output 9.12.1

 

   ActivePositionProperty = outerposition

   ALim = [0 1]

   ALimMode = auto

   AmbientLightColor = [1 1 1]

   Box = on

   CameraPosition = [12.5664 0.000251729 17.3205]

   CameraPositionMode = auto

   CameraTarget = [12.5664 0.000251729 0]

   CameraTargetMode = auto

   CameraUpVector = [0 1 0]

   CameraUpVectorMode = auto

   CameraViewAngle = [6.60861]

   CameraViewAngleMode = auto

   CLim = [0 1]

   CLimMode = auto

   Color = [1 1 1]

   CurrentPoint = [ (2 by 3) double array]

   ColorOrder = [ (7 by 3) double array]

   DataAspectRatio = [12.5664 1.19975 1]

   DataAspectRatioMode = auto

   DrawMode = normal

   FontAngle = normal

   FontName = Helvetica

   FontSize = [10]

   FontUnits = points

   FontWeight = normal

   GridLineStyle = :

   Layer = bottom

   LineStyleOrder = -

   LineWidth = [0.5]

   MinorGridLineStyle = :

   NextPlot = add

   OuterPosition = [0 0 1 1]

   PlotBoxAspectRatio = [1 1 1]

   PlotBoxAspectRatioMode = auto

   Projection = orthographic

   Position = [0.13 0.11 0.775 0.815]

   TickLength = [0.01 0.025]

   TickDir = in

   TickDirMode = auto

   TightInset = [0.0928571 0.0904762 0.00357143 0.0547619]

   Title = [1387]

   Units = normalized

   View = [0 90]

   XColor = [0 0 0]

   XDir = normal

   XGrid = off

   XLabel = [1385]

   XAxisLocation = bottom

   XLim = [0 25.1327]

   XLimMode = manual

   XMinorGrid = off

   XMinorTick = off

   XScale = linear

   XTick = [ (1 by 12) double array]

   XTickLabel = [ (12 by 2) char array]

   XTickLabelMode = auto

   XTickMode = manual

   YColor = [0 0 0]

   YDir = normal

   YGrid = off

   YLabel = [1386]

   YAxisLocation = left

   YLim = [-1.1995 1.2]

   YLimMode = manual

   YMinorGrid = off

   YMinorTick = off

   YScale = linear

   YTick = [ (1 by 11) double array]

   YTickLabel = [ (11 by 4) char array]

   YTickLabelMode = auto

   YTickMode = auto

   ZColor = [0 0 0]

   ZDir = normal

   ZGrid = off

   ZLabel = [1388]

   ZLim = [-1 1]

   ZLimMode = auto

   ZMinorGrid = off

   ZMinorTick = off

   ZScale = linear

   ZTick = [-1 0 1]

   ZTickLabel =

   ZTickLabelMode = auto

   ZTickMode = auto

 

   BeingDeleted = off

   ButtonDownFcn =

   Children = [ (2 by 1) double array]

   Clipping = on

   CreateFcn =

   DeleteFcn =

   BusyAction = queue

   HandleVisibility = on

   HitTest = on

   Interruptible = on

   Parent = [9]

   Selected = off

   SelectionHighlight = on

   Tag =

   Type = axes

   UIContextMenu = []

   UserData = []

   Visible = on

 

 

Code 9.12.2

 

figure(17)

x = linspace(0,4*(2*pi),100);

y = sin(x);

plot(x,y);

plot(x,y,'g-');

hold on

x_offset = 0;

y_offset = .2;

axis([min(x)-x_offset, max(x)+x_offset, ...

    min(y)-y_offset, max(y+y_offset)]);

plot(x,y,'o','color','r','markersize',6,...

    'markeredgecolor','k','markerfacecolor','r');

xlabel('Time');

ylabel('Happiness');

title('Life has its ups and downs.');

set(gca,'xtick',[2:2:24]);

 

shg

 

Output 9.12.2

 

 

 

Code 9.12.3

 

figure(18)

plot(x,y,'g-');

hold on

x_offset = 0;

y_offset = .2;

axis([min(x)-x_offset, max(x)+x_offset, …

      min(y)-y_offset, max(y+y_offset)]);

plot(x,y,'o','color','r','markersize',6,...

    'markeredgecolor','k','markerfacecolor','r');

xlabel('Time');

ylabel('Happiness');

title('Life has its ups and downs.');

set(gca,'xtick',[]);

set(gca,'ytick',[]);

 

 

Output 9.12.3

 

 

 

top of page

9.13      Plotting data points with error bars

 

 

Code 9.13.1

 

figure(19)

x= [1:10];

y = [4 11 25 65 141 191 313 301 487 673];

sd = [52 53 49 59 60 58 55 57 53 61];

box on

hold on

errorbar(x,y,sd,'k','markersize',18)

plot(x,y','w-',x,y,'k.','markersize',18)

shg

 

Output 9.13.1

 

 

 

top of page

9.14 Generating polar plots

 

Code 9.14.1:

 

figure(20)

clear h i

h= [0:.1:2]*pi;

polar(h,h,'ko');

shg

 

Output 9.14.1:

top of page

9.15 Generating histograms

 

Code 9.15.1:

 

figure(21)

randn('state',sum(100*clock))

h = randn(1,2000);

[N,X] = hist(h,6)

hist(h)

colormap([.5 .5 .5])

brighten(.75)

 

Output 9.15.1:

 

    

N =

 

    17    47   171   384   460   468   272   131    41     9

 

X =

 

   -2.7307   -2.0986   -1.4665   -0.8344   -0.2023    0.4298    1.0619    1.6940    2.3261    2.9582

 

 

top of page

9.16 Generating bar graphs

 

Code 9.16.1:

 

figure(22)

a = [[3 4 5 6 7 6 5 4 3]];

barh(a)

colormap([.5 .5 .5])  % gray bars

%  colormap([0 0 0]   % black bars

%  colormap([1 1 1])  % white bars

%  colormap([1 0 0])  % red bars

%  colormap([0 1 0])  % green bars

%  colormap([0 0 1])  % blue bars

brighten(.15)

ylim([0 ,10])

xlim([0 8])

 

 

Output 9.16.1:

 

 

 

top of page

9.17 Exporting and printing figures

 

 

Code 9.17.1:

 

figure(23)

plot([1:10],[1:10].^-3,'k-o')

print –f23 -r600 -djpeg my_first_figure_print

 

figure(24)

plot([1:10],[1:10].^-2,'k-s')

print -f24 –r800 -dtiff my_second_figure_print

 

ls *.jpg

ls *.tif

 

Output 9.17.1:

 

 

 

my_first_figure_print.jpg 

 

my_second_figure_print.tif

 

 

top of page

9.18 Generating other kinds of graphs and getting and setting figure properties

 

Code 9.18.1:

 

set(gcf, ‘position’, [464 581 672 504])