1
$\begingroup$

I have the following graph:

Graph[
    {1, 2, 3, 4},
    {{1, 2}, {1, 3}, {1, 4}} // Map[Apply[UndirectedEdge]],
    VertexWeight -> {10, 20, 30, 40},
    VertexLabels -> Placed["VertexWeight", Center],
    VertexSize -> Medium
]

which is displayed as follows:

A sample graph

But what I would like is to have the weights inside the circles, and the names, i.e., {1, 2, 3, 4}, just outside each circle.

What is the best way to achieve that?

Thanks in advance.

$\endgroup$
3
$\begingroup$

A simple way is to draw the graph twice with different labels:

Show[
 Graph[{1, 2, 3, 4},
    UndirectedEdge @@@ {{1, 2}, {1, 3}, {1, 4}},
    VertexWeight -> {10, 20, 30, 40},
    VertexLabels -> #,
    VertexSize -> Medium] & /@
  {"Name", Placed["VertexWeight", Center]}]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thanks! I had tried VertexLabels -> {"Name", Placed["VertexWeight", Center]}, but did not think to render the graph twice. $\endgroup$ Dec 8 '21 at 18:38
2
$\begingroup$

If getting a Graphics object is ok Bob Hanlon's method is the cleanest way I can think of.

If you need a Graph object with multiple vertex labels, you can do it in a number of ways, including:

1.

g = Graph[{1, 2, 3, 4},
  UndirectedEdge @@@ {{1, 2}, {1, 3}, {1, 4}} ,
  VertexWeight -> {10, 20, 30, 40}, 
  VertexSize -> Medium];

 Graph[g, VertexLabels -> 
   {v_ :> Placed[{AnnotationValue[{g, v}, VertexWeight], v}, {Center, {After, Above}}]}] 

enter image description here

2.

(AnnotationValue[{g, #}, VertexLabels] = 
  Placed[{AnnotationValue[{g, #}, VertexWeight], #}, {Center, {After, Above}}]) & /@
  VertexList[g];
g

enter image description here

3.

vWeights = AssociationThread[Range[4], {10, 20, 30, 40}];

Graph[{1, 2, 3, 4},
 UndirectedEdge @@@ {{1, 2}, {1, 3}, {1, 4}} ,
 VertexWeight -> Values @ vWeights, 
 VertexLabels -> {v_ :>  
    Placed[{vWeights @ v, "Name"}, {Center, {After, Above}}]}, 
  VertexSize -> Medium] 

enter image description here

$\endgroup$
5
  • $\begingroup$ Your first method is very good. Thanks! $\endgroup$ Dec 9 '21 at 7:35
  • $\begingroup$ @kglr: Is there some way to show the $2$ to be on the RHS of the node like the others? $\endgroup$
    – Moo
    Dec 9 '21 at 14:09
  • 1
    $\begingroup$ @Moo, the relative positions (with respect to the vertex positions) of all four labels are the same. $\endgroup$
    – kglr
    Dec 9 '21 at 17:39
  • $\begingroup$ @kglr: I totally missed that, however, visually, it is not very clean looking. $\endgroup$
    – Moo
    Dec 9 '21 at 17:41
  • 1
    $\begingroup$ @Moo, perhaps you can try something like Placed[{AnnotationValue[{g, v}, VertexWeight], v}, {Center, {1.25, .75}}]. $\endgroup$
    – kglr
    Dec 9 '21 at 17:47

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.