The Wayback Machine - https://web.archive.org/web/20111126140213/http://www.mathworks.com:80/help/techdoc/creating_guis/bropmbk-1.html
Skip to Main Content Skip to Search
Product Documentation

GUI that Displays and Graphs Tabular Data

About the tableplot Example

The tableplot example GUI presents data in a three-column table (a uitable object) and enables the user to plot any column of data as a line graph. When the user selects data values in the table, the plot displays markers for the selected observations. This technique is called data brushing, and is available in MATLAB. (see Marking Up Graphs with Data Brushing in the Data Analysis documentation.) The data brushing performed by this GUI does not rely on MATLAB data brushing, because that feature does not apply to uitables. The GUI, with its main components called out, looks like this when you first open it.

The table displays MATLAB sample data (count.dat) containing hourly counts of vehicles passing by at three locations. The example does not provide a way to change the data except by modifying the tableplot.mmain function to read in a different data set and then manually assign appropriate column names and a different title for the plot. A more natural way to add this capability is to allow the user to supply input arguments to the GUI to identify a data file or workspace variable, and supply text strings to use for column headers.

The tableplot main function creates a GUI figure with the following UI components:

Techniques Explored in the tableplot Example

The example demonstrates some ways to interact with a uitable and the data it holds:

A 2-D axes displays line graphs of the data in response to selecting check boxes and in real time, the results of selecting observations in the table.

To coordinate plot creation and removal and data brushing, uicontrol callbacks pass in arguments specifying one or more handles of each other and of graphic objects. The following table describes the callbacks and how they use object handles.

UI ObjectHandleCallback TypeCallback SignatureRemarks
uitablehtableCell
Selection
Callback
{@select_callback}Sets x,y,z values for nonselected markers to empty; makes markers for eventdata visible.
Check box Callback{@plot_callback,1}Plots a line graph of column 1 data.
Check boxCallback{@plot_callback,2}Plots a line graph of column 1 data.
Check boxCallback{@plot_callback,3}Plots a line graph of column 1 data.
MarkershmkrsUsed by table select_callback to brush selected table data on plot.
Static
text
hpromptPrompt displayed in axes that disappears when user plots data.
Static
text
Label for the row of check boxes

The following figure shows the results of plotting two columns and selecting the five highest values in each of the columns.

The circle markers appear and disappear dynamically as the user selects cells in the table. You do not need to plot lines in order to display the markers. Lines are individually plotted and removed via the three check boxes.

View and Run the tableplot Code

If you are reading this example in the MATLAB Help browser, you can access its files by clicking the following links. If you are reading on the Web or in a PDF, go to the corresponding section in the MATLAB Help Browser to use the links.

If you intend to modify the layout or code of this GUI example, you should first save a copy of its code in your current folder (You need write access to your current folder to do this.) Click on the following links to copy the example files to your current folder and open them.

  1. Click here to copy the tableplot.m file to your current folder

  2. edit tableplot or click here to open the code in the Editor

If you just want to run the GUI and inspect its code, follow these steps:

  1. Click here to add the example files to the MATLAB path (only for the current session).

  2. Click here to run the tableplot GUI.

  3. Click here to display the GUI code file in the Editor (read-only).

Set Up and Interact with the uitable

This example has one file, tableplot.m, that contains its main function plus two subfunctions (uicontrol callbacks). The main function raises a figure and populates it with uicontrols and one axes. The figure's menu bar is hidden, as its contents are not needed.

% Create a figure that will have a uitable, axes and checkboxes
figure('Position', [100, 300, 600, 460],...
       'Name', 'TablePlot',...  % Title figure
       'NumberTitle', 'off',... % Do not show figure number
       'MenuBar', 'none');      % Hide standard menu bar menus

The main tableplot function sets up the uitable is immediately after loading a data matrix into the workspace. The table's size adapts to the matrix size (matrices for uitables must be 1-D or 2-D).

% Load some tabular data (traffic counts from somewhere)
count = load('count.dat');
tablesize = size(count);    % This demo data is 24-by-3

% Define parameters for a uitable (col headers are fictional)
colnames = {'Oak Ave', 'Washington St', 'Center St'};
% All column contain numeric data (integers, actually)
colfmt = {'numeric', 'numeric', 'numeric'};
% Disallow editing values (but this can be changed)
coledit = [false false false];
% Set columns all the same width (must be in pixels)
colwdt = {60 60 60};
% Create a uitable on the left side of the figure
htable = uitable('Units', 'normalized',...
                 'Position', [0.025 0.03 0.375 0.92],...
                 'Data',  count,... 
                 'ColumnName', colnames,...
                 'ColumnFormat', colfmt,...
                 'ColumnWidth', colwdt,...
                 'ColumnEditable', coledit,...
                 'ToolTipString',...
                 'Select cells to highlight them on the plot',...
                 'CellSelectionCallback',{@select_callback});

The columns have arbitrary names (set with the ColumnName property). All columns are specified as holding numeric data (the ColumnFormat property) and set to a width of 60 pixels (the ColumnWidth property is always interpreted as pixels). A tooltip string is provided, and the count matrix is passed to the table as the Data parameter. Most of the uitable properties are defaulted, including the CellEditCallback property and the related ColumnEditable property (causing table cells to be noneditable).

Next, set up an axes on the right half of the figure. It plots lines and markers in response to the user's actions.

% Create an axes on the right side; set x and y limits to the
% table value extremes, and format labels for the demo data.
haxes = axes('Units', 'normalized',...
             'Position', [.465 .065 .50 .85],...
             'XLim', [0 tablesize(1)],...
             'YLim', [0 max(max(count))],...
             'XLimMode', 'manual',...
             'YLimMode', 'manual',...
             'XTickLabel',...
             {'12 AM','5 AM','10 AM','3 PM','8 PM'});
title(haxes, 'Hourly Traffic Counts')   % Describe data set
% Prevent axes from clearing when new lines or markers are plotted
hold(haxes, 'all')

Next, create the lineseries for the markers with a call to plot, which graphs the entire count data set (which remains in the workspace after being copied into the table). However, the markers are immediately hidden, to be revealed when the user selects cells in the data table.

% Create an invisible marker plot of the data and save handles
% to the lineseries objects; use this to simulate data brushing.
hmkrs = plot(count, 'LineStyle', 'none',...
                    'Marker', 'o',...
                    'MarkerFaceColor', 'y',...
                    'HandleVisibility', 'off',...
                    'Visible', 'off');

The main function goes on to define three check boxes to control plotting of the three columns of data and two static text strings. You can see the code for this when you display tableplot.m.

The Cell Selection Callback

The code for the CellSelectionCallback, which shows and hides markers on the axes, is

function select_callback(hObject, eventdata)
    % hObject    Handle to uitable1 (see GCBO)
    % eventdata  Currently selected table indices
    % Callback to erase and replot markers, showing only those
    % corresponding to user-selected cells in table. 
    % Repeatedly called while user drags across cells of the uitable

        % hmkrs are handles to lines having markers only
        set(hmkrs, 'Visible', 'off') % turn them off to begin
        
        % Get the list of currently selected table cells
        sel = eventdata.Indices;     % Get selection indices (row, col)
                                     % Noncontiguous selections are ok
        selcols = unique(sel(:,2));  % Get all selected data col IDs
        table = get(hObject,'Data'); % Get copy of uitable data
        
        % Get vectors of x,y values for each column in the selection;
        for idx = 1:numel(selcols)
            col = selcols(idx);
            xvals = sel(:,1);
            xvals(sel(:,2) ~= col) = [];
            yvals = table(xvals, col)';
            % Create Z-vals = 1 in order to plot markers above lines
            zvals = col*ones(size(xvals));
            % Plot markers for xvals and yvals using a line object
            set(hmkrs(col), 'Visible', 'on',...
                            'XData', xvals,...
                            'YData', yvals,...
                            'ZData', zvals)
        end
    end

To view the select_callback code in the Editor, click here.

The rows and columns of the selected cells are passed in eventdata.Indices and copied into sel. For example, if all three columns in row three of the table are selected,

eventdata = 
    Indices: [3x2 double]

sel =
     3     1
     3     2
     3     3

If rows 5, 6, and 7 of columns 2 and 3 are selected,

eventdata = 
    Indices: [6x2 double]

sel =
     5     2
     5     3
     6     2
     6     3
     7     2
     7     3

After hiding all the markers, the callback identifies the unique columns selected. Then, iterating over these columns, the row indices for the selection are found; x-values for all row indices that don't appear in the selection are set to empty. The vector of x-values is used to copy y-values from the table and specify dummy z-values. (Setting the z-values ensures that the markers plot on top of the lines.) Finally, the x-, y-, and z-values are assigned to the XData, YData, and ZData of each vector of markers, and the markers are made visible once again. Only markers with nonempty data display.

The user can add or remove individual markers by Ctrl+clicking table cells. If the cell is highlighted in this manner, its highlighting disappears, as does its marker. If it is not highlighted, highlighting appears and its marker displays.

The Plot Check Box callback

The three Plot check boxes all share the same callback, plot_callback. It has one argument in addition to the standard hObject and eventdata parameters:

It also uses handles found in the function workspace for the following purposes:

Keying on the column argument, the callback takes the following actions.

The plot_callback code is as follows. To view this code in the Editor, click here.

function plot_callback(hObject, eventdata, column)
    % hObject     Handle to Plot menu
    % eventdata   Not used
    % column      Number of column to plot or clear

    colors = {'b','m','r'}; % Use consistent color for lines
    colnames = get(htable, 'ColumnName');
    colname = colnames{column};
    if get(hObject, 'Value')
        % Turn off the advisory text; it never comes back
        set(hprompt, 'Visible', 'off')
        % Obtain the data for that column
        ydata = get(htable, 'Data');
        set(haxes, 'NextPlot', 'Add')
        % Draw the line plot for column
        plot(haxes, ydata(:,column),...
            'DisplayName', colname,...
            'Color', colors{column});
    else % Adding a line to the plot
        % Find the lineseries object and delete it
        delete(findobj(haxes, 'DisplayName', colname))
    end
end

Subfunction Summary for tableplot

The tableplot example contains the callbacks listed in the following table, which are discussed in the previous section. Click a function's name to open it in the Editor window.

Function

Description

plot_callback

Called by the Plot check boxes to extract data from the uitable and plot it, and to delete lines from the plot when toggled

select_callback

Erases and then replots markers, showing only those that correspond to user-selected cells in the uitable, if any.

The select_callback uses eventdata (cell selection indices); the other callback has no event data.

Further Explorations with tableplot

You can generalize the tableplot GUI in several ways to enhance its utility:

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A; sessions led by MATLAB experts.

 © 1984-2011- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS