我想使用highcharter
包在 R 中绘制一个桑基图。我在格式化它时遇到问题。这是示例。
# 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]}]
相同但 with"A"
而不是["A"]
etc. 将起作用。JS 中的证明在这个jsfiddle中。
我尝试将 JavaScript 嵌入 plot with htmlwidgets::JS
,但它不起作用:
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
考虑在这种情况下需要的系列属性?