简体   繁体   English

图表:按列内容的颜色顶点

[英]R igraph: Color Vertices by column content

I am using igraph to plot a graph from SQL Server. 我正在使用igraph从SQL Server绘制图形。 I am providing as input a 3 column table: 我提供3列表格作为输入:

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

My R script looks like this: 我的R脚本如下所示:

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. 图的边缘将显示所需的颜色,但顶点本身不显示-理想情况下,我希望“ to”顶点为“颜色”列中指示的颜色。 I don't care about the 'from's color (it can be the default orange). 我不在乎'from'的颜色(它可以是默认的橙色)。

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. 在png线之前,但这会产生看上去是随机顶点颜色的颜色。

This depends on how you created your graphdf. 这取决于您创建graphdf的方式。 Are the columns strings or factors? 列是字符串还是因子? I will show solutions for both cases. 我将展示这两种情况的解决方案。

graphdf contains strings graphdf包含字符串

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

graphdf contains factors graphdf包含因素

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 . 唯一的区别是,使用它们时,必须将as.character应用于所有因素。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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