如何在R googleVis sankey图表中更改节点和链接颜色
如何在R googleVis sankey图表中更改节点和链接的颜色?并且链接与其原始节点具有相同的颜色?
How can node and link colors be changed in R googleVis sankey chart? And link having the same color as its originating node?
library(googleVis)
datSK <- data.frame(From=c(rep("A",3), rep("B", 3)),
To=c(rep(c("X", "Y", "Z"),2)),
Weight=c(5,7,6,2,9,4))
Sankey <- gvisSankey(datSK, from="From", to="To", weight="Weight",
options=list(
sankey="{link: {color: { fill: '#d799ae' } },
node: { color: { fill: '#a61d4c' },
label: { color: '#871b47' } }}"))
plot(Sankey)
一旦您必须为来自2个原始节点的链接着色,您将需要2种颜色的链接. 另外,您总共有5个节点,因此需要5种颜色.
As soon as you have to color links from 2 originated nodes you'll need 2 colors for links. Also you have 5 nodes in total, so you'll need 5 colors for them.
让我们创建2个JSON格式的数组,并为节点和链接添加颜色
Lets create 2 arrays in JSON format with colors for nodes and links
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 = ','), "]")
下一步,将该数组插入选项:
Next, insert that array into options:
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设置为'source',这意味着您希望为来自原始节点的链接着色.或者,将目标"设置为目标节点的颜色链接
Note, that in options colorMode is set to 'source' which means you would like to color links from originated nodes. Alternatively, set 'target' to color links for destinated nodes
添加多级sankey的描述
找到如何为多级sankey分配颜色有点棘手.
It is a bit tricky to find how to assign colors for multilevel sankeys.
我们需要创建其他日期框架:
We need to create other dateframe:
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))
在这里,我们只需要更改颜色数组.构建图的命令是相同的 假设我们要为节点和链接使用这些颜色:
Here we have to change only arrays of colors. Command to built plot is the same Let's assume we want these colors for the nodes and links :
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 = ','), "]")
结果将是:
最棘手的部分是了解如何分配这些颜色:
The most trickiest part is to understand how these colors are assigned:
- 以在数据集中显示的顺序(行向)分配链接
-
对于节点,在构建顺序图中分配颜色.
For the nodes colors are assigned in the order plot is built.
- 从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
More detailed information on how to format sankey diagram : https://developers.google.com/chart/interactive/docs/gallery/sankey