Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 9 down vote accepted

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

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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