Marc Bernier
Marc Bernier

Reputation: 2996

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.

Upvotes: 3

Views: 2823

Answers (1)

G5W
G5W

Reputation: 37621

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

graphdf contains strings

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

Graph 1

graphdf contains factors

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)

Upvotes: 3

Related Questions