我想使用 highcharter 在 R 中获得桑基图,其中有 3 个不同的列,显示人们在 3 个不同的年份中如何从低测量到高测量。
这是一个模拟表,显示了我如何组织我的表,以及 Sankey 的代码
dat <- cbind(c("1.Low", "1.Low","1.High", "1.High", "2.Low", "2.High", "2.High"),
c("2.Low", "2.High", "2.Low", "2.High", "3.High", "3.Low", "3.High"),
c(5,10,15,5,1,10,15))
dat<- as.data.frame(dat)
colnames(dat)<- c("from", "to", "weight")
dat$weight<- as.numeric(dat$weight)
hchart(dat, "sankey")
这让我得到了这个桑基图:
我想做三件事:
更改标签以删除标签前面的数字。我添加它们的原因是为了区分不同的列,或者假设图表只有 2 列(低和高),但我不希望在我的最终图表中出现这种情况。
**重新排序**最后一列中的“最高”和“最低”。
3.使所有“高点”为相同颜色,所有“低点”为相同颜色 - 这可能吗? - 我见过代码可以让您在设置权重的同时单独确定每个类别的颜色,但我想要其他方式,例如按名称,因为我的实际数据集有超过 100 行,并且设置每个类别是不可行的单独组合。
到目前为止,我一直在尝试摆弄 highcharter 元素,但我发现文档非常混乱,并且没有对 Sankey 有用的示例。
我已经尝试过这些字段,但不起作用。任何和所有的想法表示赞赏。
hchart(dat, "sankey") %>%
hc_add_theme(hc_theme_ggplot2()) %>%
hc_plotOptions(series = list(dataLabels = list( style = list(fontSize = "10px")))) %>%
hc_plotOptions(sankey = list(
colorByPoint = FALSE,
curveFactor = 0.5,
linkOpacity = 0.33
)) %>% hc_add_series(nodes= list(id = '1.High' , color = "green")
,list(id = '1.Low' , color = "blue")
,list(id = '2.High' , color = "green")
,list(id = '2.Low' , color = "blue")
,list(id = '3.High' , color = "green")
,list(id = '3.Low' , color = "blue"))
这是实现您想要的结果的一种方法。
to
重新排序数据集,使“低”排在前面,然后按 from
使“低”排在前面。nodes=
属性修复颜色和标签。但是,您可以使用 lapply
创建各个节点选项的 list
,而不是为每个节点手动设置这些选项。dat <- data.frame(
c("1.Low", "1.Low", "1.High", "1.High", "2.Low", "2.High", "2.High"),
c("2.Low", "2.High", "2.Low", "2.High", "3.High", "3.Low", "3.High"),
c(5, 10, 15, 5, 1, 10, 15)
)
colnames(dat) <- c("from", "to", "weight")
library(highcharter)
dat <- dat[order(
gsub("\\d+\\.\\s?", "", dat$to),
gsub("\\d+\\.\\s?", "", dat$from),
decreasing = TRUE
), ]
nodes <- unique(c(dat$from, dat$to)) |>
lapply(\(x) {
list(
id = x,
color = if (grepl("High", x)) "green" else "blue",
name = gsub("\\d+\\.\\s?", "", x)
)
})
highchart() %>%
hc_add_series(
data = dat, type = "sankey",
hcaes(from = from, to = to, weight = weight),
nodes = nodes
) |>
hc_plotOptions(
series = list(dataLabels = list(style = list(fontSize = "10px"))),
sankey = list(
curveFactor = 0.5,
linkOpacity = 0.33
)
)