1

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.

rm -rf
  • 88,781
  • 21
  • 293
  • 472
user10245
  • 53
  • 4

2 Answers2

3

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

ubpdqn
  • 60,617
  • 3
  • 59
  • 148
2

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"}}
rm -rf
  • 88,781
  • 21
  • 293
  • 472
bill s
  • 68,936
  • 4
  • 101
  • 191