Home > Mobile >  Highlighting certain elements in Igraph plot using another dataframe
Highlighting certain elements in Igraph plot using another dataframe

Time:05-05

I am trying to build a network graph. See below the example with fruits. In reality my dataset is way larger and contains different data, but for the purpose of clarity I have simplified it.

Input code

 #Create empty matrix ----
  newMatrix <- matrix(0, nrow = 5, ncol = 5)
  colnames(newMatrix) <- c("Apple", "Pear", "Orange", "Mango", "Banana")
  rownames(newMatrix) <- c("Apple", "Pear", "Orange", "Mango", "Banana")
  
  #Create dataframe ----
  newDf <- data.frame(c("Juice 1", "Juice 2", "Juice 3", "Juice 4","Juice 5"),
                      c("Banana", "Banana", "Orange", "Pear", "Apple"),
                      c("Pear", "Orange", "Pear", "Apple", "Pear"),
                      c("Orange", "Mango", NA, NA, NA))
  colnames(newDf) <- c("Juice", "Fruit 1", "Fruit 2", "Fruit 3")

m <- do.call(cbind, apply(newDf[-1], 1, \(x) if(sum(complete.cases(x)) >= 2) combn(x, m = 2) else x, simplify = F))
  g <- graph_from_data_frame(na.omit(t(m)), directed = F)
  adj.fruit <- get.adjacency(g, sparse = F)
  adj.fruit <- graph_from_adjacency_matrix(adj.fruit)
  plot(adj.fruit)

This returns the following plot of my fruits:

enter image description here

I now want to color the vertices in different colours. I have a list that specifies which should be coloured in 'light blue'. See input below:

  highlightedfruits <- data.frame(c("Apple", "Pear"))

So I want to highlight the colours of the apple and pear vertices in light blue, but I don't know how to do that. For my real data I want to use a similar dataframe, so please help me find a solution by using the dataframe.

If anyone could help would be great! Also, if you have any other tips and tricks to make it look better would be highly appreciated as well. I'm quite new to this.

Thanks!

CodePudding user response:

If you want to control the color of each vertex, you can give them a color attribite. For example

V(adj.fruit)$color <- "orange"
V(adj.fruit)[name %in% highlightedfruits[[1]] ]$color <- "lightblue"
plot(adj.fruit)

The V() function returns a vertex list which lets you do special subsetting based on different attributes. Note this actually changes the graph data itself.

  • Related