R 中的桑基图
Sankey diagram in R
尝试在 R 的 networkD3
包的帮助下制作一个相当通用的 Sankey 图。仅供参考——这里是包手册中的示例
library(networkD3)
library(jsonlite)
library(magrittr)
energy <- "https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json" %>%
fromJSON
sankeyNetwork(Links = energy$links,
Nodes = energy$nodes,
Source = "source",
Target = "target",
Value = "value",
NodeID = "name",
units = "TWh",
fontSize = 12,
nodeWidth = 30)
这导致:
我相当直接的扩展包括使用以下基础数据构建图表:
links <- structure(list(source = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 4L,
5L, 4L, 5L),
.Label = c("1", "2", "3", "4", "5"),
class = "factor"),
target = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 4L,
4L),
.Label = c("4", "5", "6", "7"),
class = "factor"),
value = c(88L, 774L, 1220L, 412L, 5335L, 96L, 3219L,
1580L, 111L, 7607L)),
row.names = c(NA, 10L),
class = "data.frame",
.Names = c("source", "target", "value"))
nodes <- structure(list(lab = c("A", "B", "C", "D", "E", "F", "G")),
row.names = c(NA, -7L),
.Names = "lab", class = "data.frame")
选择这个简单的应用程序,以便我的数据最接近地反映手动示例。当我 运行 可比函数时,虽然:
sankeyNetwork(Links = links,
Nodes = nodes,
Source = "source",
Target = "target",
Value = "value",
NodeID = "lab")
没有任何反应。我的错误是什么?
如果您在 0
处开始对 source
和 target
进行编号,这会很好用:
# First coercing elements of links to numeric, so that we can subtract 1
links[] <- lapply(links, function(x) as.numeric(as.character(x)))
links[, 1:2] <- links[, 1:2] - 1
sankeyNetwork(links, nodes, 'source', 'target', 'value', NodeID='lab')
尝试在 R 的 networkD3
包的帮助下制作一个相当通用的 Sankey 图。仅供参考——这里是包手册中的示例
library(networkD3)
library(jsonlite)
library(magrittr)
energy <- "https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json" %>%
fromJSON
sankeyNetwork(Links = energy$links,
Nodes = energy$nodes,
Source = "source",
Target = "target",
Value = "value",
NodeID = "name",
units = "TWh",
fontSize = 12,
nodeWidth = 30)
这导致:
我相当直接的扩展包括使用以下基础数据构建图表:
links <- structure(list(source = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 4L,
5L, 4L, 5L),
.Label = c("1", "2", "3", "4", "5"),
class = "factor"),
target = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 4L,
4L),
.Label = c("4", "5", "6", "7"),
class = "factor"),
value = c(88L, 774L, 1220L, 412L, 5335L, 96L, 3219L,
1580L, 111L, 7607L)),
row.names = c(NA, 10L),
class = "data.frame",
.Names = c("source", "target", "value"))
nodes <- structure(list(lab = c("A", "B", "C", "D", "E", "F", "G")),
row.names = c(NA, -7L),
.Names = "lab", class = "data.frame")
选择这个简单的应用程序,以便我的数据最接近地反映手动示例。当我 运行 可比函数时,虽然:
sankeyNetwork(Links = links,
Nodes = nodes,
Source = "source",
Target = "target",
Value = "value",
NodeID = "lab")
没有任何反应。我的错误是什么?
如果您在 0
处开始对 source
和 target
进行编号,这会很好用:
# First coercing elements of links to numeric, so that we can subtract 1
links[] <- lapply(links, function(x) as.numeric(as.character(x)))
links[, 1:2] <- links[, 1:2] - 1
sankeyNetwork(links, nodes, 'source', 'target', 'value', NodeID='lab')