r - 使用 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
和数据帧)之间没有连接。另外,这是如何解释的,因为和是索引?target
links
0
source
target
我尝试使用以下方法创建自己的桑基图:
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 中没有得到任何情节,也没有错误消息。
解决方案
数据框中的source
和target
列/变量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)
推荐阅读
- bash - 如何在命令中直接包含 echo?
- elasticsearch - 从 Elasticsearch 的小写过滤器中排除某些标记
- java - 为什么执行AudioSystem.getAudioInputStream时会出现nullpointerException?
- python-3.x - 将 LIST A 中的列表项与元组列表 LIST B 中的每个第一个元素进行比较
- infor-eam - 导出到 Excel 只得到第一个采购订单零件清单
- python - python(pycharm)numpy.load“内存错误”
- reactjs - DraftJs - 当从 EditorState.createWithContent() 添加实体时,编辑器将实体添加到错误的块中
- php - Linux 最新 suexec 错误日志消息 cmd:suspendpage.cgi
- python - 正则表达式匹配数字、字符和非字符的组合,大小在 11-15 之间
- php - PHP登录槽API(POST请求错误)