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.
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

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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With