简体   繁体   中英

R igraph: Color Vertices by column content

I am using igraph to plot a graph from SQL Server. I am providing as input a 3 column table:

from   to     color
Node1  NodeA  red
Node1  NodeB  green
Node1  NodeC  blue
Node2  NodeD  red
Node2  NodeE  green

My R script looks like this:

require(igraph)
g <- graph.data.frame(graphdf)
V(g)$label.cex <- 2
png(filename = "'+@outputFile+'", height = 3000, width = 3000, res = 100);
plot(g, vertex.label.family = "sans", vertex.size = 5)
dev.off()

The plot's edges will display with the desired colors, but the vertices themselves do not -- ideally, I want the 'to' vertex to be the color indicated in the 'color' column. I don't care about the 'from's color (it can be the default orange).

I've tried adding this (and variations):

V(g)$color <- graphdf[V(g), 3]

before the png line, but that produces what appear to be random vertex colors.

This depends on how you created your graphdf. Are the columns strings or factors? I will show solutions for both cases.

library(igraph)

## Create data 
graphdf = read.table(text="from   to     color
Node1  NodeA  red
Node1  NodeB  green
Node1  NodeC  blue
Node2  NodeD  red
Node2  NodeE  green",
header=TRUE, stringsAsFactors=FALSE)
g <- graph.data.frame(graphdf)

I will make all nodes be orange, but then adjust the colors for the destination nodes.

## Make default color orange
V(g)$color = "orange"
V(g)[graphdf$to]$color = graphdf$color

图1

The messier case is if you allowed all of the strings to become factors. The only difference here is that you must apply as.character to all of the factors when you use them .

graphdf = read.table(text="from   to     color
Node1  NodeA  red
Node1  NodeB  green
Node1  NodeC  blue
Node2  NodeD  red
Node2  NodeE  green",
header=TRUE)
g <- graph.data.frame(graphdf)

V(g)$color = "orange"
V(g)[as.character(graphdf$to)]$color = as.character(graphdf$color)
plot(g)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM