# How to make each node of a graph a button?

A newbie question this one - MMA help seems to suggest it would be possible to place a button on ( or have a button be ) each node of graph, labelled with the name of said node. I have no idea where to start with the syntax for this though...any help much appreciated.

-

It looks like you can use VertexShapeFunction to do it (also take a look at the other options for Graph). Modifying one of the examples from the documentation:

Graph[{1 -> 2, 2 -> "bob", "bob" -> 1}, VertexShapeFunction -> (Inset[
Tooltip[
Button[#2, Speak["vertex " <> ToString[#2]]],
Column[{"arguments:"}~Join~List@##]], #1] &)]


-
Excellent, thank you. – Cuboid Oct 2 '12 at 21:56

This is a more general version of amr's button-graph, with hidden button graphics, multiple button actions (print, speak, recolor) and dynamic redrawing (recoloring nodes) to showcase more advanced capabilities of Mathematica:

(* assign colors to vertices *)
colors = # -> Hue[.6, .2, .8] & /@ {1, 2, "bob"};

Dynamic[Graph[{1 -> 2, 2 -> "bob", "bob" -> 1},
VertexShapeFunction -> (
Graphics[{#2 /. colors, EdgeForm@{GrayLevel[0, .7]},
Disk[#1, .004], Black, Text[#2, #1]}, ImageSize -> 40],
{
"Speak" :> Speak@("vertex " <> ToString@#2),
"Print" :> Print@("vertex " <> ToString@#2),
"Recolor" :> (colors[[First@First@Position[colors, #2], -1]] =
Hue[RandomReal[], .2, 1])
},
Appearance -> None], #1]} &
), ImageSize -> 250], TrackedSymbols :> {colors}]


-