一旦您必须为来自 2 个起源节点的链接着色,您将需要 2 种颜色的链接。此外,您总共有 5 个节点,因此您需要 5 种颜色。
让我们以 JSON 格式创建 2 个带有节点和链接颜色的数组
colors_link <- c('green', 'blue')
colors_link_array <- paste0("[", paste0("'", colors_link,"'", collapse = ','), "]")
colors_node <- c('yellow', 'lightblue', 'red', 'black', 'brown')
colors_node_array <- paste0("[", paste0("'", colors_node,"'", collapse = ','), "]")
接下来,将该数组插入选项中:
opts <- paste0("{
link: { colorMode: 'source',
colors: ", colors_link_array ," },
node: { colors: ", colors_node_array ," }
}" )
最后绘制图表:
plot( gvisSankey(datSK, from="From", to="To", weight="Weight",
options=list(
sankey=opts)))

请注意,在选项中,colorMode 设置为“源”,这意味着您希望对来自起源节点的链接进行着色。或者,将“目标”设置为目标节点的彩色链接
编辑:添加多级 sankeys 的描述
找到如何为多级 sankeys 分配颜色有点棘手。
我们需要创建其他日期框:
datSK <- data.frame(From=c(rep("A",3), rep("B", 3), rep(c("X", "Y", "Z"), 2 )),
To=c(rep(c("X", "Y", "Z"),2), rep("M", 3), rep("N", 3)),
Weight=c(5,7,6,2,9,4,3,4,5,6, 4,8))
在这里,我们只需要更改颜色数组。构建绘图的命令是相同的让我们假设我们想要节点和链接的这些颜色:
colors_link <- c('green', 'blue', 'yellow', 'brown', 'red')
colors_link_array <- paste0("[", paste0("'", colors_link,"'", collapse = ','), "]")
colors_node <- c('yellow', 'lightblue', 'red', 'black', 'brown', 'green', 'brown')
colors_node_array <- paste0("[", paste0("'", colors_node,"'", collapse = ','), "]")
结果将是:

最棘手的部分是了解这些颜色的分配方式:
- 链接按照它们在数据集中出现的顺序分配(row_wise)

对于节点,颜色是按照构建图的顺序分配的。
- 从 A 到 X、Y、Z - 绿色
- 从 X 到 M,N - 蓝色
- 从 Y 到 M,N - 黄色
- 从 Z 到 M,N - 棕色
- 从 B 到 X、Y、Z - 红色
有关如何格式化 sankey 图的更多详细信息: https ://developers.google.com/chart/interactive/docs/gallery/sankey