rggraphggimage

geom_node_image() - Images for nodes in ggraph


I am trying to use images (e.g. country flags) in a ggraph network. I was looking to use ggimage's geom_image, however I reckon that the function needs to be adapted to work with ggraph where we do not specify the x and y coordinates.

library(tidygraph)
library(ggraph)
library(ggimage)

r <- create_notable('bull') %>%
  mutate(class = sample(letters[1:3], n(), replace = TRUE),
         image = "https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png")

ggraph(r, 'stress') + 
  geom_node_point() +
  geom_edge_link()


r %>% 
  as_tibble() %>%
  ggplot(aes(x = runif(nrow(.)), y = runif(nrow(.)))) +
  geom_image(aes(image = image))

# I would like this to work:
ggraph(r, 'stress') + 
  geom_node_image(aes(image = image)) +
  geom_edge_link()

Solution

  • It's true that ggraph does not require you to specify X and Y coordinates, but this is a convenience. The variable names are x and y. You can be explicit:

    ggraph(r, 'stress') + 
      geom_node_point(aes(x = x, y = y))
    

    And these variables are available to all other ggplot-related functions, including ggimage::geom_image().

    ggraph(r, 'stress') + 
      geom_edge_link() + 
      geom_image(aes(x = x, y = y, image = image))
    

    enter image description here