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.

Say I have a directed graph inputted in the following format in Mathematica:

g = {{1, "a", 2}, {2, "b", 1}}

I'd like to plot this graph using GraphPlot in Mathematica, which is the following syntax:

GraphPlot[{{1 -> 2, "a"}, {2 -> 1, "b"}}, VertexLabeling -> True, DirectedEdges -> True, 
    VertexCoordinateRules -> Auto, VertexLabeling -> True]

How would I swap the middle elements and the last elements in any list like g, so that g would look closer to the argument of GraphPlot?

{{1 -> 2, "a"}, {2 -> 1, "b"}} 

I have searched the Mathematica documentation but was unable to find a good way of doing this.

share|improve this question
    
All you need is a simple replacement rule: g /. {f_Integer, m_String, l_Integer} :> {f -> l, m} –  rm -rf Oct 28 '13 at 3:48
    
Thanks! That was really simple and clean. –  user10245 Oct 28 '13 at 5:00
    
Also g[[All, 1]] = Rule @@@ g[[All, {1, 3}]];g[[All, {1, 2}]] –  Mike Honeychurch Oct 28 '13 at 5:26
add comment

2 Answers 2

up vote 2 down vote accepted

rm -rf has suggested the simplest solution which matches the elements and swaps them around:

g = {{1, "a", 2}, {2, "b", 1}};
g /. {a_Integer, b_String, c_Integer} :> {a -> c, b}
{{1 -> 2, "a"}, {2 -> 1, "b"}}
share|improve this answer
add comment

Is this your intention:

Graph[Labeled[#1 \[DirectedEdge] #3, Style[#2, 20]] & @@@ g]

enter image description here

or with more formatting:

Graph[Labeled[#1 \[DirectedEdge] #3, Style[#2, 20]] & @@@ g, 
 VertexLabels -> Placed["Name", Center], VertexSize -> 0.2, 
 VertexLabelStyle -> 20]

enter image description here

share|improve this answer
    
Thanks for this-- yes, this also works, but alas I can only accept one answer. –  user10245 Oct 28 '13 at 5:00
add comment

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.