| Contents | Index |
| On this page… |
|---|
View and Run the tableplot Code Set Up and Interact with the uitable |
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.
Note You can also create GUIs with GUIDE that contain uitables. See GUI to Interactively Explore Data in a Table (GUIDE) for a GUIDE-based example of plotting data from a uitable |
The tableplot main function creates a GUI figure with the following UI components:
A uitable with three columns of data
An axes with a title
Three check boxes for plotting columns of data
Two static text strings
The example demonstrates some ways to interact with a uitable and the data it holds:
Extract column names and use them as menu items
Graph specific columns of data
Brush the graph when the user selects cells in the table
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 Object | Handle | Callback Type | Callback Signature | Remarks |
|---|---|---|---|---|
| uitable | htable | Cell 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 box | — | Callback | {@plot_callback,2} | Plots a line graph of column 1 data. |
| Check box | — | Callback | {@plot_callback,3} | Plots a line graph of column 1 data. |
| Markers | hmkrs | — | — | Used by table select_callback to brush selected table data on plot. |
| Static text | hprompt | — | — | Prompt 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.
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.
Click here to copy the tableplot.m file to your current folder
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:
Click here to add the example files to the MATLAB path (only for the current session).
Click here to display the GUI code file in the Editor (read-only).
Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. Save them to your current or other folder that you work in. |
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 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
endTo 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 three Plot check boxes all share the same callback, plot_callback. It has one argument in addition to the standard hObject and eventdata parameters:
column — An integer identifying which box (and column of data) the callback is for
It also uses handles found in the function workspace for the following purposes:
htable — To fetch table data and column names for plotting the data and deleting lines; the column argument identifies which column to draw or erase.
haxes — To draw lines and delete lines from the axes.
hprompt — To remove the prompt (which only displays until the first line is plotted) from the axes.
Keying on the column argument, the callback takes the following actions.
It extracts data from the table and calls plot, specifying data from the given column as YData, and setting its DisplayName property to the column's name.
It deletes the appropriate line from the plot when a check box is deselected, based on the line's DisplayName property.
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
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 |
|---|---|
Called by the Plot check boxes to extract data from the uitable and plot it, and to delete lines from the plot when toggled | |
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.
You can generalize the tableplot GUI in several ways to enhance its utility:
Allow the user to edit table values.
Enabling editing by the user involves setting the uitable ColumnEditable property to true and, if necessary, coding its CellEditCallback. Editing data cells might require updating the line plot and cell selection markers if they are visible; to make this happen, however, you must provide code to replot graphics similar to the code in the existing plot_callback and select_callback.
Note The refreshdata function updates graphs when workspace variables that they display change. However, as the tableplot GUI contains its own data sources, you cannot use refreshdata within it for this purpose. |
Parse command-line arguments specifying a workspace variable to load into the table when the GUI opens
If the user specifies the name of a workspace variable when calling tableplot, its opening function can validate the argument. (Does it exist? Is it numeric? Is it one- or two-dimensional?) If the argument passes these tests, assign the uitable Data property to it and proceed to the next step.
Parse a second command-line argument intended for specifying uitable column names.
The optional column names should be supplied as a cell matrix of strings the same width as the data matrix. If this argument is not supplied, the operation should assign default column names, such as Col_1, Col_2, ... Col_n.
Add check boxes for plotting columns if the number of columns in the uitable expands, and remove them when columns go away.
You can add new check boxes when adding columns to the table and remove them if the table contracts. If you allow the uitable and the GUI to grow wider, you can continue to space the check boxes the same as they are currently, up to the point where the GUI becomes too wide to fit within the screen. If you keep the width of the uitable constant, you need some other mechanism to select columns to plot, such as checking items on a menu or selecting names from a list box.
Incorporate a uicontrol and a dialog to select a workspace variable to load in after the GUI is running.
For example, you can add a list box that interrogates the current folder using whos and select from the variables only those that are numeric and with dimensionality no greater than 2 to populate the table. When the user selects one of these items in the list box, that variable is loaded and replaces the uitable data. The operation should assign default column names for the new data.
Provide a dialog to let the use change column names on the fly.
If you do this, the callback will need to change the column headers in the uitable, and (if you implement line plotting with menus, as described above) change menu items as well.
Provide an option to normalize values before plotting them or display a semilog plot instead of a linear plot
The data matrix might have columns with very different data ranges and units of measure. Therefore, one challenge of plotting columns of arbitrary matrices together is to specify appropriate limits for the y-axis. (The x-axis always portrays the row indices.) By default, the axes' YLim property is 'auto', so that the y-limits adjust to span the minimum and maximum of the data being plotted. If you provide code to set limits, it should be robust enough to require changing limits as seldom as possible. Alternatively, you can transform column data values before plotting them in some way, for example, by normalizing or standardizing them.
You can also allow the user to generate a semilog plot, which has the effect of compressing the range of y-values. This affects the plot_callback, which needs logic to decide whether to call plot or semilogy based on the state of some uicontrol.
![]() | GUI with Axes, Menu, and Toolbar | A GUI That Manages List Data | ![]() |

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 |