如何在不使用visNetwork::visIgraph**?**着色的情况下设置图节点子集的颜色?
目前,我的函数vis_graph_prototyping生成所需的图,除了选定的绿色节点也有它们相关的边以绿色着色。如何使这些边沿以默认颜色显示,并且只有我通过E(g, P = as.vector(t(linkages))或E(g, path = pathway, directed = TRUE)分别选择的红色边?
当前输出的图像显示在可再现的示例R片段下面。
rnd_dag <- function(p = 25, p_edge = 0.2, weighted = FALSE, seed = 123) {
if (seed) set.seed(seed)
A <- matrix(0, p, p)
A[lower.tri(A)] <- sample(c(0, 1), p*(p-1)/2, replace = TRUE,
prob = c(1 - p_edge, p_edge))
if (weighted) {A[A == 1] <- runif(length(A[A == 1]), min = -1, max = 1)}
return(A)
}
linkages <- matrix(c(9, 1,
12, 1,
11, 2), ncol = 2, byrow = TRUE)
vis_graph_prototyping <- function(A, linkages = NULL, pathway = NULL) {
g <- graph_from_adjacency_matrix(A, mode = "directed", weighted = TRUE)
stopifnot(is.null(linkages) || is.null(pathway))
if (!is.null(linkages)) {
g <- set_vertex_attr(g, name = "color",
index = unique(as.vector(linkages)),
value = "green") %>%
set_edge_attr(name = "color",
index = E(g, P = as.vector(t(linkages)), directed = TRUE),
value = "red")
} else if (!is.null(pathway)) {
g <- set_vertex_attr(g, name = "color", index = pathway, value = "green") %>%
set_edge_attr(name = "color",
index = E(g, path = pathway, directed = TRUE), value = "red")
}
visIgraph(g, layout = "layout_with_sugiyama") %>%
visOptions(highlightNearest = list(enabled = TRUE, hover = TRUE),
nodesIdSelection = TRUE)
}
vis_graph_prototyping(rnd_dag(12), linkages = linkages)

发布于 2022-05-07 23:53:41
您可以设置颜色,以便必须设置它们(而不是从节点继承它们)。
创建图形对象时,在设置红色边缘之前,将颜色设置为默认颜色。你可以找到这里的默认颜色。
我唯一的改变就是你的职责。看看这个。
vis_graph_prototyping <- function(A, linkages = NULL, pathway = NULL) {
g <- graph_from_adjacency_matrix(A, mode = "directed", weighted = TRUE)
stopifnot(is.null(linkages) || is.null(pathway))
if (!is.null(linkages)) {
# message(print(edges))
# message(print(linkages))
g <- set_vertex_attr(g, name = "color",
index = unique(as.vector(linkages)),
value = "green") %>%
set_edge_attr(name = "color",
index = E(g), # <----- all edges
value = "#97C2FC") %>% # <----- default blue
set_edge_attr(name = "color",
index = E(g, P = as.vector(t(linkages)), directed = TRUE),
value = "red")
} else if (!is.null(pathway)) {
g <- set_vertex_attr(g, name = "color", index = pathway, value = "green") %>%
set_edge_attr(name = "color",
index = E(g, path = pathway, directed = TRUE), value = "red")
message(" from null path ")
message(E(g))
}
visIgraph(g, layout = "layout_with_sugiyama") %>%
visOptions(highlightNearest = list(enabled = TRUE, hover = TRUE),
nodesIdSelection = TRUE)
}

https://stackoverflow.com/questions/71190397
复制相似问题