首页 > 解决方案 > 使用 R 中的 networkD3 在 RStudio 查看器中不显示桑基图

问题描述

基于以下示例:

# Load package
library(networkD3)

# Load energy projection data
URL <- "https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json"
Energy <- jsonlite::fromJSON(URL)


# Now we have 2 data frames: a 'links' data frame with 3 columns (from, to, value), and a 'nodes' data frame that gives the name of each node.
head( Energy$links )
head( Energy$nodes )

# Thus we can plot it
p <- sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 12, nodeWidth = 30)
p

我不明白这个例子中的索引是如何发生的,因为和nodes name索引(source和数据帧)之间没有连接。另外,这是如何解释的,因为和是索引?targetlinks0sourcetarget

我尝试使用以下方法创建自己的桑基图:

name<-c("J","B","A")
nodes3<-data.frame(name)
source<-c("B","B","J")
target<-c("A","A","B")
value<-c(5,6,7)
links3<-data.frame(source,target,value)

p <- sankeyNetwork(Links = data.frame(links3), Nodes = data.frame(nodes3), Source = "source",
                   Target = "target", Value = "value", NodeID = "name",
                   units = "cases", fontSize = 12, nodeWidth = 30)
p

但是,虽然一切似乎都在运行,但我在 RStudio Viewer 中没有得到任何情节,也没有错误消息。

标签: rsankey-diagramhtmlwidgetsnetworkd3

解决方案


数据框中的sourcetarget列/变量links应该是数字,其中每个值是它在nodes数据框中引用的节点的索引(0 索引,而不是 R 中通常的 1 索引)。

例如,在第一个例子中......

head(Energy$links)
#>   source target   value
#> 1      0      1 124.729
#> 2      1      2   0.597
#> 3      1      3  26.862
#> 4      1      4 280.322
#> 5      1      5  81.144
#> 6      6      2  35.000

head(Energy$nodes)
#>                   name
#> 1 Agricultural 'waste'
#> 2       Bio-conversion
#> 3               Liquid
#> 4               Losses
#> 5                Solid
#> 6                  Gas

第一个链接从 0(nodes数据框的第 0 行,即名为“Agriculture 'waste'”的节点)到 1(nodes数据框的第 1 行,即名为“Bio-conversion”的节点)

所以对于第二个例子,你可以通过......

name<-c("J","B","A")
nodes3<-data.frame(name)
source<-c("B","B","J")
target<-c("A","A","B")
value<-c(5,6,7)
links3<-data.frame(source,target,value)



links3$source_id <- match(links3$source, nodes3$name) - 1
links3$target_id <- match(links3$target, nodes3$name) - 1

library(networkD3)

sankeyNetwork(Links = links3, Nodes = nodes3, 
          Source = "source_id", Target = "target_id", Value = "value", 
          NodeID = "name", units = "cases", fontSize = 12, nodeWidth = 30)

在此处输入图像描述


推荐阅读