This example shows how to customize the GraphPlot
data cursor to display extra node properties of a graph.
GraphPlot
objectCreate a GraphPlot
graphics object for a random directed graph. Add an extra node property wifi
to the graph.
rng default
G = digraph(sprandn(20, 20, 0.05));
G.Nodes.wifi = randi([0 1], 20, 1) == 1;
h = plot(G);
Enable data cursor mode by selecting the Data Cursor item in the Tools menu.
With data cursor mode enabled, click a node in the graph to bring up the cursor display. The data cursor allows you to select nodes in a graph plot and view properties of the nodes. By default, the data cursor for an undirected graph displays the node ID number and degree. For directed graphs, the display includes the node ID number, in-degree, and out-degree.
To display extra node properties, such as wifi
, the data cursor callback function needs to be modified. For general information on using and customizing data cursors, see Interactively Explore Plotted Data.
Customize the text displayed by the data cursor by writing a new data cursor callback function.
1. Save the function GraphCursorCallback.m
in your current directory:
function output_txt = GraphCursorCallback(obj,event_obj,NodeProperties) % Display the position of the data cursor % obj Currently not used (empty) % event_obj Handle to event object % output_txt Data cursor text (character vector or cell array of character vectors). h = get(event_obj,'Target'); pos = get(event_obj,'Position'); ind = find(h.XData == pos(1) & h.YData == pos(2), 1); output_txt = {['Node ' num2str(ind)], ... ['Wifi: ' num2str(NodeProperties.wifi(ind))]};
A standard data cursor callback function accepts two input arguments. GraphCursorCallback
accepts an additional input argument, NodeProperties
, so that the data cursor gains access to the extra node properties in the graph, such as wifi
.
2. Connect the GraphCursorCallback
function to the data cursor by changing the UpdateFcn
property of the data cursor manager object. This command uses an anonymous function to pass the G.Nodes
table as the third input to GraphCursorCallback
. This technique only takes a snapshot of the G.Nodes
table, so if the graph properties subsequently change, then you need to change the UpdateFcn
property again.
hdt = datacursormode; hdt.UpdateFcn = @(obj,event_obj) GraphCursorCallback(obj,event_obj,G.Nodes);
3. Now that GraphCursorCallback
is connected to the data cursor, delete any old data tips in the plot, then reenable data cursor mode and select a node. The new display of the data cursor includes the wifi
node property as defined in GraphCursorCallback
.
datacursormode
| digraph
| graph