rigraphggraph

Placement of geom_node labels outside vertices with different sizes


I aim to draw a circular network where the labels of the vertices are placed outside the vertices. While this can be done relatively easily for vertices with similar sizes, this is getting more difficult for vertices with different sizes.

My expected result is to set the labels similar to the left chart below. Is there a neat way to achieve this?

Examples:

example

Code to reproduce networks:

# packages
library(ggraph)
library(igraph)

# create example data
set.seed(123)
adj_mat <- matrix(runif(49, 0, 7), nrow=7)
colnames(adj_mat) <- letters[1:7]
size <- runif(7, 0.1, 0.5)

# create graph object
g <- graph_from_adjacency_matrix(adj_mat, weighted = T, diag = T)

# set size of vertices
V(g)$size <- size

# plot with equal sizes
p <- ggraph(g, layout = "circle") +
  geom_edge_link() +
  geom_node_circle(aes(r=0.1), fill = "orange") +
  theme(aspect.ratio = 1)

p +
  geom_node_text(aes(label = name), nudge_x = p$data$x * .2, nudge_y = p$data$y * .2)

# plot with different sizes
p <- ggraph(g, layout = "circle") +
  geom_edge_link() +
  geom_node_circle(aes(r=size), fill = "orange") +
  theme(aspect.ratio = 1)

p +
  geom_node_text(aes(label = name), nudge_x = p$data$x * .25, nudge_y = p$data$y * .25)


Solution

  • You could use a bit of trigonometry to calculate the angle of each node from the centre, then nudge the text outwards in that direction by an amount determined by the size variable. This would draw text right on the edge of the nodes, so we can add, say, a distance of 0.1 in the radial direction to get the text in a pretty position.

    p <- ggraph(g, layout = "circle") +
      geom_edge_link() +
      geom_node_circle(aes(r=size), fill = "orange") +
      theme(aspect.ratio = 1)
    
    p +
      geom_node_text(aes(label = name), size = 8,
                     nudge_x = cos(atan2(p$data$y, p$data$x)) * (0.1 + p$data$size),
                     nudge_y = sin(atan2(p$data$y, p$data$x)) * (0.1 + p$data$size))
    

    enter image description here