I want to build a small GUI, where the user can select either a single edge or a single node of a graph. I got to this point:

selection = {};

Dynamic[Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 
   3 \[UndirectedEdge] 1},
  PlotLabel -> selection,
  VertexShapeFunction -> (EventHandler[
      Disk[#1, .1], {"MouseClicked" :> (selection = {#2})}] &),
  EdgeShapeFunction -> (EventHandler[
      Arrow[#1, .1], {"MouseClicked" :> (selection = {#2})}] &),
  GraphHighlight -> selection,
  GraphHighlightStyle -> "Thick",
  ImageSize -> 200

Which gives the following (note that I already highlighted an edge by clicking on it for clarity):

Mathematica graphics

Now if I try to click on one of the nodes, the dynamic visualization breaks, giving back the unevaluated result:

Mathematica graphics

Note, that the GraphHighlight and PlotLabel options correctly registered the click, as the selected node is on their right hand sides. Any idea what the difference is in this context between edges and nodes? The two clicking functionality are meant to be identical.


The reason why it fails is because of GraphHighlight. If you're highlighting a single vertex, then it expects an atom and not a list. In other words, it needs to be something like GraphicsHighlight -> 1 instead of GraphicsHighlight -> {1}. However, this is not the case for edges, where even a single edge can be supplied wrapped in a list.

So the culprit here is the {#2} in VertexShapeFunction -> (...), and all you need to do to fix it is remove the {}. The following code works.

DynamicModule[{selection = {}},
 Dynamic[Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 
    3 \[UndirectedEdge] 1}, PlotLabel -> selection,
   VertexShapeFunction -> (EventHandler[Disk[#1, .1], 
       "MouseClicked" :> (selection = #2;)] &),
   EdgeShapeFunction -> (EventHandler[Arrow[#1, .1], 
       "MouseClicked" :> (selection = #2;)] &), 
   GraphHighlight -> selection, GraphHighlightStyle -> "Thick", 
   ImageSize -> 200]]

enter image description here

  • $\begingroup$ And I wonder why is that so. It definitely smells like someone forgot to add the func[single_?AtomQ]:=func[{single}] piece of code... $\endgroup$ – István Zachar Jan 20 '12 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.