LESSON 4: Subplots, multiple axes, and insets

FOCUS QUESTION: How can I combine graphs to make effective comparisons?

This lesson demonstrates different ways to combine plots to compare data.

In this lesson you will:
  • Read a comma separated value data file.
  • Extract columns as new variables.
  • Use insets to give emphasize.
  • Produce a plot mosaic using subplot.
  • Use multiple axes on the same plot.
Chest X-ray of TB patient

Contents


DATA FOR THIS LESSON

File Description
CaliforniaTB.csv
  • The data set is a comma separated value data file containing the following 3 columns:
    • the year
    • the number of California tuberculosis cases in that year
    • the number of cases per 100,000 people (infection rate) in California for that year
  • The data covered the period 1985-2007 and was extracted from a report produced by the Tuberculosis Control Branch of the California Department of Public Health. The full report can be found at http://www.cdph.ca.gov/data/statistics/Documents/TB_Report_2007.pdf .
CaliforniaTBGender.csv
  • The data set is a comma separated value data file containing the following 5 columns:
    • the year
    • the number of male California tuberculosis cases in that year
    • the number of cases per 100,000 males (infection rate) in California for that year
    • the number of female California tuberculosis cases in that year
    • the number of cases per 100,000 females (infection rate) in California for that year
  • The data covered the period 1998-2007 and was extracted from a report produced by the Tuberculosis Control Branch of the California Department of Public Health. The full report can be found at http://www.cdph.ca.gov/data/statistics/Documents/TB_Report_2007.pdf .

SETUP FOR LESSON 4


EXAMPLE 1: Read a comma separated value data file

Create a new cell in which you type and execute:

   TB = csvread('CaliforniaTB.csv');
   TBGender = csvread('CaliforniaTBGender.csv');

You should see 2 variables in the Workspace Browser:


Draw a picture of the TB array and carefully label the columns. What happens if you execute the command plot(TB)?  


EXAMPLE 2: Define meaningful variables for each column of TB

Create a new cell in which you type and execute:

   years = TB(:, 1);          % Pick out all the values in the first column of TB
   cases = TB(:, 2);          % Pick out all the values in the second column of TB
   infectionRate = TB(:, 3);  % Pick out all the values in the third column of TB

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 3: Plot the number of TB cases versus year

Create a new cell in which you type and execute:

   figure('Name', 'TB cases')    % Create a new figure window
   plot(years, cases)            % Plot year versus number of TB cases
   xlabel('Years');              % Label the x-axis
   ylabel('Cases')               % Label the y-axis
   title('Tuberculosis in California (1985-2007)');  % Put a title on graph

You should see a Figure Window containing a plot of TB cases versus year:


Create a new cell right here (beginning of a cell starts with %%). Write MATLAB code to plot casesGender versus yearsGender. Label the graph and put a title and an appropriate legend on it.


EXAMPLE 4: Create a plot of TB cases with an infection rate inset


EXAMPLE 5: Open a previously created figure from a script

  open TBInset.fig;

You should see a Figure Window containing an edited plot with an inset as shown below.


Save the figure you created in the exercise for Example 3 as TBGenderInset.fig. Add an inset with a pie chart of casesGender. Save the final result. Create a new cell right and open TBGenderInset.fig so that when you execute the lesson script, you will see this figure.


EXAMPLE 6: Plot infection rate and cases on different axes using subplot

Create a new cell in which you type and execute:

   figure ('Name', 'TB subplot');   % Create a new figure
   subplot(1, 2, 1)                 % Define the left subplot
   plot(years, cases);              % Plot the left subplot
   xlabel('Years')                  % Label x-axis of this subplot
   ylabel('Cases')                  % Label y-axis of this subplot
   subplot(1, 2, 2)                 % Define the right subplot
   plot(years, infectionRate);      % Plot the second plot
   xlabel('Years')                  % Label x-axis of this subplot
   ylabel('Infection rate (cases/100,000)') % Label y-axis of this subplot

You should see a Figure Window containing two side-by-side plots:


Create a new cell right here (beginning of a cell starts with %%) and copy the code for Example 6. Add the graph of casesGender versus yearsGender to the first subplot. Add an appropriate legend too. Note: the code between each subplot command is treated as though it were a separate figure. You will need to add your code between the two subplot commands. Recall that plotting multiple graphs on the same axis requires you to use hold on and hold off.


EXAMPLE 7: Compute the population of California from the data

Create a new cell in which you type and execute:

   population = 100000.*cases./infectionRate;   % California's population

You should see a population variable in your Workspace.


EXAMPLE 8: Use a subplot that spans two positions

Create a new cell in which you type and execute:

   figure ('Name', 'TB spanned subplot');   % Create a new figure
   subplot(2, 2, [1,3])             % Define the left subplot
   plot(years, population./1E6);    % Plot population in left subplot
   xlabel('Years')                  % Label x-axis of this subplot
   ylabel('Population (in millions)')  % Label y-axis of this subplot
   subplot(2, 2, 2)                % Define the upper right subplot
   plot(years, cases./1000);       % Plot cases in the upper right subplot
   ylabel('Thousands of cases')    % Label y-axis of this subplot
   subplot(2, 2, 4)                % Define the lower right subplot
   plot(years, infectionRate);     % Plot infection rate in the upper right subplot
   xlabel('Years')                 % Label x-axis of this subplot
   ylabel('Cases/10^5 people')     % Label y-axis of this subplot

You should see a Figure Window containing three plots:


EXAMPLE 9: Plot rate and cases on the same graph using vertical different axes

Create a new cell in which you type and execute:

   figure ('Name', 'TB yy-plot')
   ax = plotyy(years, cases, years, infectionRate);  % Two vertical axes
   xlabel(ax(1), 'Years')      % Label x corresponding to left vertical axis
   ylabel(ax(1), 'Cases')      % Label left vertical y axis
   ylabel(ax(2), 'Infection rate in cases per thousand')  % Label right vertical y axis
   title('Tuberculosis in California: 1985-2007')

You should see a Figure Window containing an unedited plot with two y-axes:


EXAMPLE 10: Combine a line graph and bar chart on the same graph using different vertical axes

Create a new cell in which you type and execute:

   figure ('Name', 'TB yy bar plot')
   [axn, h1, h2] = plotyy(years, cases, years, infectionRate, 'bar', 'plot');  % Two vertical axes
   xlabel(axn(1), 'Years')      % Label x corresponding to left vertical axis
   ylabel(axn(1), 'Cases')      % Label left vertical y axis
   ylabel(axn(2), 'Infection rate in cases per thousand')  % Label right vertical y axis
   title('Tuberculosis in California: 1985-2007')
   set(h1, 'FaceColor', [0.8, 0.8, 0.8])  % Fix the bar colors so light gray
   set(h2, 'LineWidth', 2)      % Make line thicker on line graph


Carefully compare the plots of EXAMPLE 9 and EXAMPLE 10. Why do these plots look so different even though they plot the same thing?  


SUMMARY OF SYNTAX

MATLAB syntax Description
A./B produces an array that is the result of dividing each element of A by the corresponding element of B. The A and B array must be the same size, or at least one of them must be a scalar. If one of the arrays is a scalar, it is expanded to be the same size as the other.
csvread('myfile.csv') reads a file named myfile.csv whose values are separated by commas into the MATLAB workspace.
plotyy(x1, y1, x2, y2) creates a plot with two vertical axes, one appearing on the left and one appearing on the right. The left axis plots x1 versus y1, and the right axis plots x2 versus y2. Use plotyy when y1 and y2 are in different units or are not of comparable sizes.
ax = plotyy(x1, y1, x2, y2) creates a plot with two vertical axes, one appearing on the left and one appearing on the right. The ax variable is a two-element vector holding the handles to the left and right axes, respectively. Use ax(1) to change the axis properties (e.g., label, tick marks) of the left axis. Use ax(2) to change the axis properties of the right axis.
[ax, h1, h2] = plotyy(x1, y1, x2, y2) creates a plot with two vertical axes, one appearing on the left and one appearing on the right. The ax variable is a two-element vector holding the handles to the left and right axes, respectively. The h1 variable holds a handle to the left axis plot, while the h2 variable holds a handle to the right axis plot. Use these two handles to set properties of the graphs themselves, such as the color or the line width.
subplot(n, m, k) specifies a tabular plot layout with n rows and m columns. This particular command specifies the k-th plot in the tableau. Plots are arrayed from left to right by row.


This lesson was written by Kay A. Robbins of the University of Texas at San Antonio and last modified on 06-Sep-2011. Please contact krobbins@cs.utsa.edu with comments or suggestions. The image, which originated from the US Department of Health and Human Services, is a chest X-ray of a patient with advanced tuberculosis. The image is available on Wikipedia as <http://en.wikipedia.org/wiki/File:Tuberculosis-x-ray-1.jpg>.