我在R中构建了一个图形,我成功地使用if语句在颜色上着色一些顶点,我使用tkplot
函数来获得更好的可视化。
现在我有以下图表:
FROM TO
A B
A D
B C
B F
D E
E G
E H
H M
H L
L N
和以下顶点集
E
L
我需要绘制图表着色连接传入和输出在E和L中的红色,而所有其他在黑色中。
为了清楚起见,我需要红色以下连接线
FROM TO
D E
E G
E H
H L
H M
有解决方案吗?
答案 0 :(得分:1)
只需使用您想要的颜色创建一个颜色矢量,对应B
中的边缘:
library(igraph)
B = matrix( c("A" ,"A", "B" ,"B","D","E", "E", "H", "H", "L", "B","D","C","F","E","G","H","M","L","N"), ncol=2)
B<- data.frame(B)
grf<- graph.data.frame (B, directed =TRUE, vertices=NULL)
error<-array(c("E", "L"))
V(grf)$color <- ifelse(V(grf)$name %in% error, "red", "yellow")
col = rep("black", nrow(B))
col[B$X1 == "E" | B$X2 == "L"] <- "red"
# or
# col[B$X1 %in% c("E", "L") | B$X2 %in% c("E", "L")] <- "red"
plot(grf, edge.color = col)
# or
# tkplot(grf, edge.color = col)
答案 1 :(得分:1)
使用edge.color
属性不是唯一的方法。
您还可以为每个边缘设置color
属性,例如:
(可以找到有关V(g)
和E(g)
函数的更多信息here)
library(igraph)
# initialize the graph
DF <-
read.table(text=
"FROM TO
A B
A D
B C
B F
D E
E G
E H
H M
H L
L N",header=T,stringsAsFactors=T)
g <- graph.data.frame(DF)
# set a color (black) attribute on all edges
E(g)$color <- 'black'
# set red color for the edges that have an incident vertex in the set 'E,L'
nodesSeq <- V(g)[name %in% c('E','L')]
E(g)[inc(nodesSeq)]$color <- 'red'
tkplot(g)