我正在尝试使用igraph合并R中的两个图形。理想情况下,我会创建g1
和g2
的顶点联合,仅保留g1
的边。应该基于label
属性创建此联合。我想我可以在合并之前简单地从g2
删除所有边缘,使用类似这样的东西:
g2 %>% delete_edges(seq(1, length(E(g2)), by = 1))
但是,当我创建一个这样的联盟时:
g.union <- graph.union(g1, g2, byname=F)
我得到的图表包含属性id_1
,id_2
,label_1
,label_2
,weight_1
,weight_2
...这不是我想要的。我需要保留g1
中的所有顶点和边,只添加g2
中g1
中缺少的g1
个顶点。保留那些添加顶点的所有属性。
任何帮助表示赞赏!
修改
@MrFlick,我无法分享这些图表,但一个简单的例子是这样的:
我有graph
[
directed 1
node
[
id 1
label "it2igcryfm862x"
mydetails "somedetails1"
]
node
[
id 2
label "it0l2xa53eu1w3"
mydetails "somedetails2"
]
node
[
id 3
label "iszyxcopnao380"
mydetails "somedetails3"
]
edge
[
source 1
target 2
weight 1
]
edge
[
source 1
target 3
weight 2
]
edge
[
source 2
target 3
weight 1
]
]
g2
和graph
[
directed 1
node
[
id 1
label "it2igcryfm862x"
mydetails "somedetails1"
]
node
[
id 2
label "it0l2xa53eu1w3"
mydetails "somedetails2"
]
node
[
id 3
label "iszyxcopnao380"
mydetails "somedetails3"
]
node
[
id 4
label "it0lhztmkln4n6"
mydetails "somedetails4"
]
edge
[
source 1
target 2
weight 1
]
edge
[
source 1
target 3
weight 3
]
edge
[
source 2
target 3
weight 2
]
edge
[
source 2
target 4
weight 2
]
edge
[
source 3
target 4
weight 1
]
]
g3
我需要的是graph
[
directed 1
node
[
id 1
label "it2igcryfm862x"
mydetails "somedetails1"
]
node
[
id 2
label "it0l2xa53eu1w3"
mydetails "somedetails2"
]
node
[
id 3
label "iszyxcopnao380"
mydetails "somedetails3"
]
node
[
id 4
label "it0lhztmkln4n6"
mydetails "somedetails4"
]
edge
[
source 1
target 2
weight 1
]
edge
[
source 1
target 3
weight 2
]
edge
[
source 2
target 3
weight 1
]
]
def handle_click(event):
if treeview.identify_region(event.x, event.y) == "separator":
return "break"
#...
treeview.bind('<Button-1>', handle_click)
答案 0 :(得分:1)
这是一个可重现的例子
library(igraph)
set.seed(1)
g1 <- make_(ring(10), with_vertex_(label = LETTERS[1:10]))
V(g1)$color = "red"
g2 <- make_(ring(15), with_vertex_(label = LETTERS[1:15]))
V(g2)$color <- "cyan"
你需要
保留g1中的所有顶点和边,只添加那些顶点 来自g2中缺少的g1。保持那些添加的所有属性 顶点。
一种方法:
v <- V(g2)[!V(g2)%in%V(g1)]
g3 <- add_vertices(g1, length(v), attr = vertex.attributes(g2, v))
以下是两张原始图表和结果的样子:
par(mfrow=c(1,3))
lapply(mget(ls(pattern = "^g\\d")), plot)
答案 1 :(得分:1)
您的原始代码似乎接近于您提供的示例。
library(igraph)
### Recreating your example
par(mfrow = c(2,2), mar=c(0.5,0.5,0.5,0.5))
g1 = graph_from_edgelist(matrix(c(1,2,1,3,2,3), ncol=2, byrow=TRUE))
g1 = set_vertex_attr(g1, "label",
value=c("it2igcryfm862x", "it0l2xa53eu1w3",
"iszyxcopnao380"))
plot(g1)
box()
g2 = graph_from_edgelist(matrix(c(1,2,1,3,2,3,2,4,3,4), ncol=2, byrow=TRUE))
g2 = set_vertex_attr(g2, "label",
value=c("it2igcryfm862x", "it0l2xa53eu1w3",
"iszyxcopnao380", "it0lhztmkln4n6"))
plot(g2)
box()
## Create the desired union
g1g2 = union(g1,delete_edges(g2, E(g2)))
## Edit: Preserving labels
NewLabels = c(vertex_attr(g1, "label"),
setdiff(vertex_attr(g2, "label"), vertex_attr(g1, "label")))
g1g2 = set_vertex_attr(g1g2, "label", value=NewLabels)
plot(g1g2)
box()