我想使用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嵌入到情节中,但是它不起作用: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))
但是,这不会呈现出良好的情节。
关于R Highcharter Sankey节点列属性故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50860385/