networkD3包(请参阅herehere)允许用户创建简单的交互式网络:

# Load package
library(networkD3)

# Create fake data
src <- c("A", "A", "A", "A",
        "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J",
            "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)

# Plot
simpleNetwork(networkData)

有没有一种方法可以指定我希望src向量中的所有元素都是某种颜色,同时允许target向量中的所有元素都变成另一种颜色?这将使我能够在视觉上区分网络中的src节点和target节点。
simpleNetwork()当前似乎不支持此功能(但我希望有人可以通过自制脚本帮助我):

javascript - R networkD3软件包: node coloring in simpleNetwork()-LMLPHP

一个类似但不相关的问题是asked here

最佳答案

这是使用forceNetwork控制节点颜色的方法。注意,这仍然不会告诉您链接的方向,因为某些节点是某些链接的源,而另一些则是目标的-因此,您需要以某种方式重新考虑该逻辑。但是无论如何,这里是控制节点的颜色。

# Load package
library(networkD3)
library(dplyr) # to make the joins easier

# Create fake data
src <- c("A", "A", "A", "A",
         "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J",
            "E", "F", "G", "H", "I")
networkData <- data.frame(src, target, stringsAsFactors = FALSE)

nodes <- data.frame(name = unique(c(src, target)), stringsAsFactors = FALSE)
nodes$id <- 0:(nrow(nodes) - 1)


# create a data frame of the edges that uses id 0:9 instead of their names
edges <- networkData %>%
   left_join(nodes, by = c("src" = "name")) %>%
   select(-src) %>%
   rename(source = id) %>%
   left_join(nodes, by = c("target" = "name")) %>%
   select(-target) %>%
   rename(target = id)

edges$width <- 1

# make a grouping variable that will match to colours
nodes$group <- ifelse(nodes$name %in% src, "lions", "tigers")

# simple with default colours
forceNetwork(Links = edges, Nodes = nodes,
             Source = "source",
             Target = "target",
             NodeID ="name",
             Group = "group",
             Value = "width",
             opacity = 0.9,
             zoom = TRUE)

# control colours with a JS ordinal scale
# edited 20 May 2017 with updated code from Renal Chesak's answer:
ColourScale <- 'd3.scaleOrdinal()
            .domain(["lions", "tigers"])
           .range(["#FF6900", "#694489"]);'

forceNetwork(Links = edges, Nodes = nodes,
             Source = "source",
             Target = "target",
             NodeID ="name",
             Group = "group",
             Value = "width",
             opacity = 0.9,
             zoom = TRUE,
             colourScale = JS(ColourScale))

javascript - R networkD3软件包: node coloring in simpleNetwork()-LMLPHP

关于javascript - R networkD3软件包: node coloring in simpleNetwork(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35280218/

10-12 17:05