gpt4 book ai didi

R Highcharter Sankey 节点列属性问题

转载 作者:行者123 更新时间:2023-12-02 19:25:56 25 4
gpt4 key购买 nike

我想使用 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))

这会产生以下图片: Out-of-box

我希望 B 节点位于中间,以便更好地查看绘图。因此,我尝试通过操作 Highcharts 系列中的 nodescolumn 属性来实现此目的:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com