使用R中的networkD3在RStudio Viewer中不显示Sankey图表

问题描述 投票:0回答:1

基于以下示例:

# 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数据帧的targetlinks之间没有连接)。另外,由于0source是索引,因此如何解释target

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

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中我没有看到任何图,也没有错误消息。

r sankey-diagram htmlwidgets networkd3
1个回答
0
投票

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

例如,在第一个示例中……

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行,即名为“农业'废物”的节点)到1(nodes数据帧的第1行,即名为“ Bio-转换“)

因此,对于第二个示例,您可以使用...实现]

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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.