TransWikia.com

Placing and styling EdgeLabels in Graph

Mathematica Asked on April 10, 2021

I have:

Graph[{1 [DirectedEdge] 1, 1 [DirectedEdge] 2, 1 [DirectedEdge] 3, 
  2 [DirectedEdge] 1, 2 [DirectedEdge] 2, 3 [DirectedEdge] 1, 
  3 [DirectedEdge] 2, 3 [DirectedEdge] 3},
 VertexStyle -> Orange,
 VertexSize -> 0.3, VertexLabelStyle -> Directive[Red, Italic, 16],
 VertexLabels -> Placed["Name", Center],
 EdgeStyle -> Black,
 EdgeLabels -> {1 [DirectedEdge] 1 -> Placed["0.9", 0.5]}]

Which produces this image:

enter image description here

I’d like to center the 0.9 on the arrow below the vertex labeled 1 with a white background. How can I do this? And I’d like to increase its font size.

One Answer

Version 9.0:

g =  Graph[{1 -> 1, 1 -> 2, 1 -> 3, 2 -> 1, 2 -> 2, 3 -> 1, 3 -> 2, 3 -> 3}, 
  VertexStyle -> Orange, VertexSize -> 0.3, 
  VertexLabelStyle -> Directive[Red, Italic, 16], 
  VertexLabels -> Placed["Name", Center], EdgeStyle -> Black, 
  EdgeLabels -> {(1 -> 1) -> Placed[Framed[Style["0.9", 14, Italic, Bold, Blue], 
     Background -> White, FrameStyle -> White], "Middle"]}]

enter image description here

Version 11:

If you don't mind having a Graphics object (instead of a Graph object), you can post-process Show[g] to adjust the label position:

Show[g] /. ImageScaled[{_, _}] :> ImageScaled[{.5, -.7}]

enter image description here

If you do need to have a Graph object, you can extract the edge shape and edge label from ToBoxes[g], make the necessary adjustments and use the resulting expression as the value of EdgeShapeFunction for the edge 1->1:

edgeshape = Cases[ToBoxes[g], {ab : _ArrowBox, ib: _InsetBox} :> 
  {ab, ib /. ImageScaled[{_, _}] :> ImageScaled[{.5, -.7}]}, {0, ∞}][[1]];

Row[{g, SetProperty[{g, 1->1}, {EdgeLabels -> None, EdgeShapeFunction -> (edgeshape &)}]}]

enter image description here

Answered by kglr on April 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP