Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to make the edges and vertices of a Graph interactive, a simple demonstration is to change their colors:

DynamicModule[{col = Green},
     Style[1, col], 
       {"MouseClicked" :> (col = col /. {Red -> Green, Green -> Red})}],
    2, 3, 4, 5},
   {1 -> 2, 1 -> 3, 2 -> 4,
     Style[2 -> 5, col], 
       {"MouseClicked" :> (col = col /. {Red -> Green, Green -> Red})}]

The above code generates a graph that has two clickable objects (one edge, one vertex) however they both change color when one of the objects is clicked. I suspected this is due to my EventHandler code and the events would trigger whenever the Graph is clicked. The color change event is not thrown, however, if one of the other edges/vertices is clicked so I'm a bit stuck.

As an aside, I used Rule instead of DirectedEdge which seems to work although I don't know if this is the right way to make a graph.

share|improve this question
up vote 2 down vote accepted

Let's use some functionalities Graphs are equiped with:

col[_] := Red;
b = Button[Style[#, col[#]], col[#] = col[#] /. {Red -> Green, Green -> Red}] &;

  {1, b@2, 3, b@4, 5},
  {1 -> 2, 1 -> 3, b[2 -> 4], 2 -> 5}]

enter image description here

Graph allows us to put inside Style Button etc. This is the effect.

Perfect situation for You would be if DynamicModule is avalible, unfortunatelly it is not. Then You could create similar function to that above with scoped col and with different initialization value for each color. I will try to work around that.

share|improve this answer

One possibility is to use different names for the color styles:

      col[1]], {"MouseClicked" :> (col[1] = 
         col[1] /. {Red -> Green, Green -> Red})}], 2, 3, 4, 
    5}, {1 -> 2, 1 -> 3, 2 -> 4, 
     Style[2 -> 5, 
      col[2]], {"MouseClicked" :> (col[2] = 
         col[2] /. {Red -> Green, Green -> Red})}]}],
 Initialization :> {col[_] := Green}]
share|improve this answer

Your Answer


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.