LESSON 2: Working with line graphs

FOCUS QUESTION: How do I display trends in data?

This lesson shows you different ways to plot the rows and columns of a table or array using line graphs.

In this lesson you will:
  • Read multiple variables from a .mat file.
  • Plot arrays using line graphs.
  • Call the MATLAB sum function to add up the rows or columns.
  • Manipulate time series to plot on different time scales.
  • Use the colon operator (:) to make an array into a single column.
  • Use the transpose operator (') to flip an array to needed orientation.
Young child with chicken pox

Contents


DATA FOR THIS LESSON

File Description
NYCDiseases.mat
  • The data set contains of the monthly totals of the number of new cases of measles, mumps, and chicken pox for New York City during the years 1931-1971.
  • The data is organized into the following variables:
    • measles - an array containing the monthly cases of measles
    • mumps - an array containing the monthly cases of mumps
    • chickenPox - an array containing the monthly cases of chicken pox
    • years - a vector containing the years 1931 through 1971
  • The data was extracted from the Hipel-McLeod Time Series Datasets Collection, available at http://www.stats.uwo.ca/faculty/aim/epubs/mhsets/readme-mhsets.html.
  • The data originally appeared in: Yorke, J.A. and London, W.P. (1973). "Recurrent Outbreaks of Measles, Chickenpox and Mumps", American Journal of Epidemiology, Vol. 98, pp. 469.

SETUP FOR LESSON 2


EXAMPLE 1: Load the New York City contagious disease data set

Create a new cell in which you type and execute:

   load NYCDiseases.mat;    % Load the NYC disease data

You should see 4 variables in the Workspace Browser:

In the space below, draw a picture of the measles array and label its rows and columns.  


EXAMPLE 2: Define appropriate variables for analysis

Create a new cell in which you type and execute:

   measles1931 = measles(1, :);  % Measles cases in 1931 (row 1 of measles)
   measles1941 = measles(11, :); % Measles cases in 1941 (row 11 of measles)
   measlesMay = measles(:, 5);   % Measles cases in May (column 5 of measles)
   measlesSpring = measles(:, [3, 4, 5]); % Measles for March, April, May

You should see 4 variables in the Workspace Browser:

In the space below: Enter your definitions in this cell and execute the cell to create these variables.


EXAMPLE 3: Plot the measles cases for 1931

Create a new cell in which you type and execute:

   figure                       % Create a new figure window
   plot(measles1931);           % Plot 1931 measles (y-axis) against 1..12
   xlabel('Month')              % Always label your axes
   ylabel('Case count')
   title('Measles cases NYC: 1931')

You should see a Figure Window with the measles cases for 1931:


Create a new cell right here (beginning of a cell starts with %%). Write MATLAB code to plot the number of measles cases for 1941.


EXAMPLE 4: Plot the measles cases for the month of May

Create a new cell in which you type and execute:

   figure                    % New figure
   plot(years, measlesMay);  % Plot May measles (y-axis) against years (1931 .. 1971)
   xlabel('Year');           % Label the x-axis
   ylabel('Case count');     % Label the y-axis
   title('NYC measles cases for month of May');  % Put a title on the graph

You should see a Figure Window with a single line graph:


Create a new cell right here (beginning of a cell starts with %%). Write MATLAB code to plot the number of mumps cases for April.


EXAMPLE 5: Plot the spring measles cases

Create a new cell in which you type and execute:

   figure                       % New figure
   plot(years, measlesSpring);  % Plot spring measles (y-axis) against years (1931 .. 1971)
   xlabel('Year');              % Label the x-axis
   ylabel('Case count');        % Label the y-axis
   title('NYC measles cases for spring');  % Put a title on the graph
   legend({'March', 'April', 'May'})  % Use a legend to identify multiple lines

You should see a Figure Window with a single line graph:


Create a new cell right here (beginning of a cell starts with %%). Write MATLAB code to plot the summer chicken pox cases.


EXAMPLE 6: Compare the measles cases for the years 1931 and 1941

Create a new cell in which you type and execute:

   figure                       % New figure
   hold on                      % Draw multiple graphs in same figure
   plot(measles1931, '-sb');    % Draw 1931 measles with blue(b) squares(s)
   plot(measles1941, '-ok');    % Draw 1941 measles with black(k) circles(o)
   hold off                     % No more graphs
   xlabel('Month')              % Label x axis
   ylabel('Case count')         % Label y axis
   title('Measles cases NYC')   % Put a title on the graph
   legend({'1931', '1941'})     % Use a legend to identify two graphs

You should see a Figure Window with a two line graphs:

In the space below, make 3 observations about the graphs of EXAMPLE 6 (in bullet point form).  


EXAMPLE 7: Adding the rows or columns of an array to summarize data

Create a new cell in which you type and execute:

   measlesByMonth = sum(measles);    % Sum each column of measles
   measlesByYear = sum(measles, 2);  % Sum each row of measles
   measlesTotal = sum(measles(:));   % Find the total number of measles cases

You should see 3 variables in the Workspace Browser:

In the space below: Enter your definitions in this cell and execute the cell to create these variables.


EXAMPLE 8: Plot yearly total (in thousands of cases) of measles by year

Create a new cell in which you type and execute:

   figure                                 % Create a new figure window
   plot(years, measlesByYear./1000);      % Draw a line graph
   xlabel('Year');                        % Label the x-axis
   ylabel('Total cases (in thousands)');  % Label the y-axis
   title('NYC measles cases');            % Put a title on the graph

You should see a Figure Window with a rescaled y-axis:


EXAMPLE 9*: Try plotting the entire measles array

Create a new cell in which you type and execute:

   figure                       % Create a new figure window
   plot(measles);               % Draw a line graph

You should see a Figure Window with 12 line graphs (the columns of measles):

In the space below, briefly explain why this graph is not acceptable.  


EXAMPLE 10*: Attempt to plot all the measles data as a single time series

Create a new cell in which you type and execute:

   figure                        % Create a new figure window
   plot(measles(:));             % Draw a line graph of end-to-end columns

You should see a Figure Window with a single line graph (but it isn't what you want):

In the space below, briefly explain what this line graph represents.  


EXAMPLE 11*: Correctly plot the measles data as a single time series

Create a new cell in which you type and execute:

   measlesFlip = measles';    % Flip measles to make rows into columns
   figure                     % Create a new figure window
   plot(measlesFlip(:));      % Draw a line graph

You should see a Figure Window with a single line graph:


EXAMPLE 12*: Define the x-axis scale for the single time series

Create a new cell in which you type and execute:

   yearStart = 1931;                       % Start of the scale
   yearInc = 1/12;                         % Scale has one month intervals
   yearEnd = 1972 - yearInc;               % End of the scale
   yearScale = yearStart:yearInc:yearEnd;  % Yearly scale (with month increments)

You should see yearStart, yearInc, yearEnd, and yearScale variables in the Workspace Browser.


EXAMPLE 13*: Plot the measles data as a single time series, setting x-axis scale

Create a new cell in which you type and execute:

   figure                                    % Create a new figure window
   plot(yearScale, measlesFlip(:)./1000);    % Draw a line graph
   xlabel('Year');                           % Label the x-axis
   ylabel('Cases (in thousands)');           % Label the y-axis
   title('NYC measles cases');               % Put a title on the graph

You should see a Figure Window with a single line graph:


SUMMARY OF SYNTAX

MATLAB syntax Description
sum(x) sums the columns of the array x.
sum(x, 1) sums the columns of the array x.
sum(x, 2) sums the rows of the array x.
a:b forms a row with the values a, a+1, ..., b.
a:inc:b forms a row with the values a, a+inc, a+2*inc, ..., b.
title('string') puts string as a title above the plot of the current axis.
xlabel('string') uses string as the label for the x-axis of the current axis.
ylabel('string') uses string as the label for the y-axis of the current axis.
legend adds an identifying annotation to the current figure.
A./B creates a new array whose elements are the elements of the array A divided by the corresponding elements of the array B. If B consists of a single number, then each element of A is divided by the value of B.
x(:) creates a single column containing the columns of the array x positioned end-to-end (i.e., the first column of x, followed by the second column of x, etc.).
x' creates a new array in which the values of x are flipped along its main diagonal so that the rows become the columns and the columns become the rows. x' is called the transpose of x.


This lesson was written by Kay A. Robbins of the University of Texas at San Antonio and last modified on 17-Jan-2011. Please contact krobbins@cs.utsa.edu with comments or suggestions. The photo is Child with chickenpox, image 7135384 from <http://www.istockphoto.com>.