Home > database >  igraph: How to assign a gradient of colors to edges and vertices?
igraph: How to assign a gradient of colors to edges and vertices?

Time:12-24

I am trying to assign the same color gradient to both, edges and vertices on igraph using R. The gradient should color from low to high counts in the V(data_graph)$Counts portion.

Some reproducible data:

library(igraph) 
data <- data.frame(Country = c("Africa", "Argentina", "Bolivia", "Chile", "France", "Guam", "Poland", "Greenland", "Switzerland", "UK", "US"), 
               Counts = c(2,2,8,1,5,3,3,15, 15,30,35), 
               Pillar = c(rep("SoS", 4), rep("CNES", 4), rep("STE", 3)))

data_center <- setNames(data.frame("c", 1, "Sos"), names(data))
data_vtx <- rbind(data_center, data)
data_rel <- data.frame(from = head(data_vtx$Country, 1), 
                    to = data_vtx$Country[2:12])

which produces the following graph:

data_graph <- graph_from_data_frame(data_rel,  directed = FALSE, data_vtx)

plot(data_graph, 
 layout = layout.fruchterman.reingold(data_graph),
 vertex.size = round(V(data_graph)$Counts/1.5, 2), 
 vertex.label.color = "black",
 edge.curved = 0.3)

However, next I would like to apply the same color gradient to both, the vertex and the edges based on the V(data_graph)$Counts. What I need is something similar to the scale_color_gradient2 command from ggplot2.

Example:

scale_color_gradient2(low = “blue”, mid = “yellow”, high = “red”, midpoint = mean(V(data_graph)$Counts))

The closest I have found is the following post: Graph with colored edges

CodePudding user response:

Assuming your palette is known. If not see Gradient of n colors ranging from color 1 and color 2. Add the Palette to the data and data_center data frames. Add vertex and edge colors to the plot() statement.

library(igraph)

data <- data.frame(Country = c("Africa", "Argentina", "Bolivia", "Chile", "France", "Guam", "Poland", "Greenland", "Switzerland", "UK", "US"), 
               Counts = c(2,2,8,1,5,3,3,15, 15,30,35), 
               Pillar = c(rep("SoS", 4), rep("CNES", 4), rep("STE", 3)),
              Palette = rainbow(11)  # <<< 
         )

data_center <- setNames(data.frame("c", 1, "Sos", "black"), names(data)) # <<< center color  is black
data_vtx <- rbind(data_center, data)
data_rel <- data.frame(from = head(data_vtx$Country, 1), 
                         to = data_vtx$Country[2:12]
            )
                    
data_graph <- graph_from_data_frame(data_rel,  directed = FALSE, data_vtx)

set.seed(202212)
plot(data_graph, layout = layout_as_star(data_graph),
 vertex.size        = round(V(data_graph)$Counts/1.5, 2), 
 vertex.color       = data_vtx$Palette,
 vertex.label.color = "black",
 edge.width         = 3,
 edge.curved        = 0.3,
 edge.color         = data$Palette
) 
  • Related