R Highcharter Sankey节点列属性问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R Highcharter Sankey节点列属性问题相关的知识,希望对你有一定的参考价值。
我想使用highcharter
包在R中绘制一个Sankey图。我在格式化时面临问题。这是一个例子。
# devtools::install_github("jbkunst/highcharter")
library(highcharter)
hc_dat <- data.frame(from = c("A", "A", "B"),
to = c("C", "B", "C"), N = c(7, 5, 5))
highchart() %>%
hc_add_series(data = hc_dat, type = "sankey",
hcaes(from = from, to = to, weight = N))
我希望B
节点处于中间位置,以便更好地了解情节。所以我试图在Highcharts系列中实现这个操纵column
的nodes
属性:
nodes_mapping <- list(list(id = "A", column = 0),
list(id = "B", column = 1),
list(id = "C", column = 2))
highchart() %>%
hc_add_series(data = hc_dat, type = "sankey",
nodes = nodes_mapping,
hcaes(from = from, to = to, weight = N))
这不会改变图片。我发现,原因如下:highcharter
使用jsonlite::toJSON
转换R
对象,它在JSON中提供了不必要的[]
,这破坏了Highcharts的行为。
jsonlite::toJSON(nodes_mapping)
# [{"id":["A"],"column":[0]},{"id":["B"],"column":[1]},{"id":["C"],"column":[2]}]
相同但使用"A"
而不是["A"]
等将起作用。 JS中的证据就在这个jsfiddle中。
我试图用htmlwidgets::JS
在javascript中嵌入JavaScript,但它不起作用:
highchart() %>%
hc_add_series(data = hc_dat, type = "sankey",
nodes = JS('[{"id":"A","column":[0]},{"id":"B","column":[1]},{"id":"C","column":[2]}]'),
hcaes(from = from, to = to, weight = N))
# empty chart
highchart() %>%
hc_add_series(data = hc_dat, type = "sankey",
JS('nodes: [{"id":"A","column":[0]},{"id":"B","column":[1]},{"id":"C","column":[2]}]'),
hcaes(from = from, to = to, weight = N))
# Error: inherits(mapping, "hcaes") is not TRUE
highchart() %>%
hc_add_series(data = hc_dat, type = "sankey",
hcaes(from = from, to = to, weight = N),
JS('nodes: [{"id":"A","column":[0]},{"id":"B","column":[1]},{"id":"C","column":[2]}]'))
# Error: Column 4 must be named
所以,我在这里被困住了。有谁知道如何让hc_add_series
考虑系列的属性,因为在这种情况下需要它?
答案
来自A-> B和B-> C的Sankey可以通过重新定义基础数据来完成:
hc_dat <- data.frame(from = c("A", "B"),
to = c("B", "C"), N = c(7, 5))
同样,您可以从A-> C定义节点
hc_dat <- data.frame(from = c("A", "B", "A"),
to = c("B", "C", "C"), N = c(5, 5, 7))
但是,这并不能提供一个很好的情节。
另一答案
正如评论中已经提到的,你可能想给networkD3
一个镜头。
以下是基于您提供的示例数据的示例。
# Create nodes and links data.frames
nodes <- data.frame(name = unique(unlist(hc_dat[, 1:2])))
links <- data.frame(
source = match(hc_dat$from, nodes$name) - 1,
target = match(hc_dat$to, nodes$name) - 1,
value = hc_dat$N)
# Draw a Sankey diagram
library(networkD3)
sankeyNetwork(
Links = links, Nodes = nodes,
Source = "source", Target = "target", Value = "value", NodeID = "name",
fontSize = 16, fontFamily = "sans-serif", nodeWidth = 30, nodePadding = 30)
以上是关于R Highcharter Sankey节点列属性问题的主要内容,如果未能解决你的问题,请参考以下文章