2015-03-31 26 views
3

如何更改R googleVis sankey图表中的节点和链接颜色?和链接具有相同的颜色作为其始发节点?如何更改R中的节点和链接颜色googleVis sankey图表

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) 

回答

6

只要您必须从2个始发节点着色链接,您需要2种颜色的链接。 另外你总共有5个节点,所以你需要5种颜色。

允许创建2个阵列JSON格式颜色为节点和链接

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))) 

enter image description here

请注意,在选项中,colorMode被设置为'source',这意味着您想对来自始发节点的链接进行着色。另外,“目标”设置为颜色链接,destinated节点

编辑:添加说明对多sankeys

这是一个有点棘手找到如何分配颜色多sankeys。

我们需要建立其他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)) 

这里我们要改变的颜色只有阵列。命令内置的情节是一样的 假设我们希望这些色彩为节点和链接:

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 = ','), "]") 

结果将是:

enter image description here

最棘手的部分是要了解这些是如何颜色被指定为:

  1. 按照它们在数据集中出现的顺序分配链接(row_wise)

enter image description here

  • 对于颜色分配在顺序的情节是建立在节点。

    • 从A到X,Y,Z - 绿色
    • 从X到M,N - 蓝色
    • 从Y到M,N - 黄色
    • 从Z到M,N - 棕色
    • 从B到X,Y,Z - 红
  • 关于如何热平衡图格式的更多的详细信息:https://developers.google.com/chart/interactive/docs/gallery/sankey

    +0

    你能扩展你的答案为[多级Sankeys(https://developers.google.com/chart/interactive/docs/gallery/sankey#multilevel-sankeys)? – zx8754 2016-04-18 12:53:26

    +0

    是否有可能从一个节点出现两种不同的颜色?换句话说,可以在不使用“source”或“target”作为colorMode的情况下设置颜色吗?请参阅:https://stackoverflow.com/questions/45291340/how-to-color-two-links-coming-out-of-the-same-node-or-going-to-the-same-node-w – 2017-07-27 16:22:45