我有一个动态网络,我想用 R shiny 和 visNetwork 来表示它。根据选择的节点,节点和边的颜色应该根据一些外部协议/数据(下面代码中的节点列表和边列表)而改变。
这对节点非常有效:我选择一个节点,在未来的所有时间步骤中,节点的颜色会根据数据而变化。为此,我使用visUpdateNodes
.
但是,当我尝试使用 对边缘进行基本相同的操作时visUpdateEdges
,它无法正常工作:不仅为节点着色,还创建了新节点(使用正确的颜色)。
一个简单的例子在这里:
library(shiny)
library(tidyverse)
library(visNetwork)
# some data - these values are for the updating process
nodeslist <- list(id1 = data_frame(R1 = c("red", "orange", "orange"), R2 = c("red",
"black", "green"), R3 = c("red", "cyan", "yellow")), id2 = data_frame(R1 = c("orange",
"red", "orange"), R2 = c("black", "red", "green"), R3 = c("orange", "red",
"yellow")), id3 = data_frame(R1 = c("orange", "orange", "red"), R2 = c("black",
"yellow", "red"), R3 = c("brown", "cyan", "red")))
edgeslist <- list(id1 = data_frame(R1 = c("red", "orange", "orange"), R2 = c("red",
"black", "green"), R3 = rep("black", 3)), id2 = data_frame(R1 = c("orange",
"red", "orange"), R2 = c("black", "red", "green"), R3 = rep("black", 3)),
id3 = data_frame(R1 = c("orange", "orange", "red"), R2 = c("black", "yellow",
"red"), R3 = rep("black", 3)))
# the updating functions
changeColorOfOtherNodes <- function(nodes, selected.node, index) {
nodes %>% mutate(color = unlist(nodeslist[[as.numeric(selected.node)]][,
index]))
}
changeColorOfEdges <- function(edges, selected.node, index) {
edges %>% mutate(color = unlist(edgeslist[[as.numeric(selected.node)]][,
index]))
}
# making the network
id <- c(1, 2, 3)
color <- rep("cyan", length(id))
nodes <- data_frame(id, color)
from <- c(1, 2, 3)
to <- c(2, 3, 1)
edges <- data_frame(from, to, color = rep("#333333", 3), value = c(2, 2, 2))
# shiny application
server <- shinyServer(function(input, output, session) {
output$netplot <- renderVisNetwork({
visNetwork(nodes, edges) %>% visOptions(nodesIdSelection = list(enabled = TRUE))
})
observe({
if (!is.null(input$netplot_selected) && input$netplot_selected > 0) {
for (i in 1:ncol(nodeslist[[as.numeric(input$netplot_selected)]])) {
# updating works well for nodes
nodes <- changeColorOfOtherNodes(nodes, input$netplot_selected,
index = i)
visNetworkProxy("netplot") %>% visUpdateNodes(nodes)
Sys.sleep(1)
# updating for edges -> new edges are creates, but don't know why
edges <- changeColorOfEdges(edges, input$netplot_selected, index = i)
visNetworkProxy("netplot") %>% visUpdateEdges(edges)
Sys.sleep(1)
print(edges)
}
}
})
})
ui <- shinyUI(fluidPage(mainPanel(visNetworkOutput("netplot"))))
shinyApp(server = server, ui = ui)
有谁知道如何正确使用 visUpdateEdges 更新节点的颜色?为什么要visUpdateEdges
创建新边缘而不是更新现有边缘?