rnetwork-programmingigraphnetwork-analysis

How to plot igraph such that each vertex is at a specified coordinates, that resembles football player positions?


I have a dataframe with 3 columns, example like this (purely hypothetical):

id <- c("Muller", "Muller", "Ter Stegen", "Musiala", "Musiala", "Musiala", "Pavard")
tid <- c("Davies", "De Ligt", "Muller", "Kimmich", "Pavard", "Lewandowski", "De Ligt")
Passes <- c(14, 5, 1, 10, 23, 4, 1)

Passes <- data.frame(id, tid, Passes)

dput(Passes)

And I have been wanting to plot this so that the vertices appear at specific coordinates in the output graph .

So far my codes are like this:

g <- graph.data.frame(Passes, directed = TRUE)
set_edge_attr(g, "weight", value= E(g)$Passes)
coords <- data.frame(id = c("Ter Stegen", "Musiala", "Davies", "Kimmich", 'De Ligt', "Lewandowski", "Muller", "Pavard"),
                     x= c(0.5, 1, 1, 1,  2, 3, 3, 3.5),
                     y= c(1, 1.8, 1.4, 1, 0.6, 1.8, 1.6, 1.2))
plot(g, vertex.size= 2, edge.arrow.size = 0.3,  vertex.label.cex = 0.8, 
     edge.curved=.2, asp = 0, vertex.label.dist=0.7, 
     layout=coords, xlim = c(0, 4), ylim = c(0, 2))

But then I keep getting errors like 'Error in norm_coords(layout, -1, 1, -1, 1) : `layout' not a matrix''

Anyone know what is wrong with my code, or can propose a better method? Thank you! It's just my actual dataframe has 32 unique ids and together there are 252 rows, I want to find an efficient way to give each unique id a position.

Thanks, Emmy


Solution

  • try

    library(tidyverse)
    new.coords <- coords %>% arrange(factor(id, levels = V(g))) %>% select(x,y) %>% as.matrix()
    
    plot(g, vertex.size= 2, edge.arrow.size = 0.3,  vertex.label.cex = 0.8, 
         edge.curved=.2, asp = 0, vertex.label.dist=0.7, 
         layout = new.coords)
    

    enter image description here