在边缘上表示常用信息

时间:2019-03-10 19:08:46

标签: r graph

我有类似这样的数据

GPS -> accurate, lost, quality
Battery ->  draining, hog, drain 
Screen ->   flickering, off
Signal ->   lost, quality

现在,我想生成一个图表,如果两个节点共享一些公共信息,则将它们连接起来,如果两个节点不共享任何信息,则不连接它们。以上数据的图形表示如下:

enter image description here

有什么线索可以在R中实现吗?

1 个答案:

答案 0 :(得分:1)

图表

Lines所示定义输入并进行转换,以便我们可以将其读取到数据帧DF中,然后拆分为列表s。然后创建ea,这是一个三列矩阵,其中包含由顶点from,顶点to和边缘标签edge_label定义的可能边。没有标签的边设置为具有edge_label NA,然后删除所有具有NA的行,给出矩阵e。最后,创建图g并将其绘制出来。

(此数据可以用二分图来表示,如该图后面的“二分图”部分所述。)

library(igraph)

# input
Lines <- "GPS -> accurate, lost, quality
Battery ->  draining, hog, drain 
Screen ->   flickering, off
Signal ->   lost, quality"

L <- sub(" ->", ",", readLines(textConnection(Lines)))
DF <- read.table(text = L, sep = ",", as.is = TRUE, 
  strip.white = TRUE, fill = TRUE)

# split DF into a list, s, whose components are named using DF[[1]]
s <- lapply(split(as.matrix(DF[, -1]), DF[[1]]), Filter, f = nzchar)

Intersect <- function(x) toString(intersect(s[[x[1]]], s[[x[2]]]))
ea <- cbind(t(combn(names(s), 2)), combn(names(s), 2, Intersect))
colnames(ea) <- c("from", "to", "edge.label")
e <- na.omit(replace(ea, !nzchar(ea), NA))

# create graph and plot
g <- graph_from_data_frame(e, vertices = names(s), directed = FALSE)
plot(g, edge.label = e[, "edge.label"], 
  vertex.color = "white", vertex.size = 35, edge.color = "black")

screenshot

二部图

另一种方法是创建二部图。

gg <- graph_from_incidence_matrix(table(stack(s)))
plot(gg, layout = layout_as_bipartite)

更新

简化。添加二部图部分。