1
$\begingroup$

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.

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

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"}}
$\endgroup$
3
$\begingroup$

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

$\endgroup$
  • $\begingroup$ Thanks for this-- yes, this also works, but alas I can only accept one answer. $\endgroup$ – user10245 Oct 28 '13 at 5:00

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.