在 R googleVis 桑基图中分配节点和链接颜色


关于

这个问题,我正在尝试使用R中的GoogleVis包在桑基图中为节点分配一组颜色,并希望与梯度模式链接。问题是我在 3 组节点中的每一组都有相同的类别,并且我无法让它合作。

datSK <- data.frame(From=c(rep("A1",3), rep("B1", 3), rep("C1", 3), rep("A2", 3), rep("B2", 3), rep("C2",3)), 
                To=c(rep(c("A2", "B2", "C2"), 3), rep(c("A3", "B3", "C3"), 3)),
                Weight=c(5,7,6,2,9,4,3,4,5))

我希望节点 A、B、C,它们出现在图表的 3 个不同部分具有相同的颜色(分别为蓝色、橙色、绿色)。

plot(gvisSankey(datSK, from="From", 
       to="To", weight="Weight",
       options=list(sankey="{
                    link: { colorMode: 'gradient', colors: ['blue', 'orange', 'green']}, 
                    node: { colors: ['blue', 'orange', 'green']}}")))

不幸的是,我无法弄清楚颜色是如何分配的。

已经

一年了,我不知道你是否还需要答案,但这是我发现的:

plot(gvisSankey(datSK, from="From", 
       to="To", weight="Weight",
       options=list(sankey="{
                    link: { colorMode: 'gradient'}, 
                    node: { colors: ['blue', 'blue', 'orange',
                                     'green','orange', 'green',
                                     'blue','orange','green']}
                             }")))

谷歌的桑基图将根据节点的外观顺序分配颜色。以下是我决定节点外观顺序的方法。基本上,我创建一个节点连接列表的字符串,拆分它们,并提取唯一的节点,然后分配颜色。

# Create a stringlist of node pairs
nodestringlist <- paste(datSK$From,datSK$To, collapse=' ')
# Split them up
nodestringvector <- strsplit(nodestringlist, split =' ')
# Find the unique nodes in order they appear
node_order <- unique(nodestringvector[[1]])
#output: "A1" "A2" "B2" "C2" "B1" "C1" "A3" "B3" "C3"

这是你想要的吗?

我想添加另一个解决方案。

# install.packages("googleVis")
library(googleVis)
# Dataframe from your example
datSK <- data.frame(
  From = c(rep("A1", 3),
           rep("B1", 3),
           rep("C1", 3),
           rep("A2", 3),
           rep("B2", 3),
           rep("C2", 3)),
  To = c(rep(c("A2", "B2", "C2"), 3),
         rep(c("A3", "B3", "C3"), 3)),
  Weight = c(5, 7, 6, 2 ,9, 4, 3, 4, 5))
# Costumize the color of nodes:
val_dat <- c()
for (i in 1:nrow(datSK)) {
  val_dat <- c(val_dat, as.character(datSK$From[i]),
               as.character(datSK$To[i]))
}
node_color <- sapply(unique(val_dat), function(set_color) {
  if (grepl('A', set_color)) return('blue')
  if (grepl('B', set_color)) return('orange')
  if (grepl('C', set_color)) return('green')
})
# Create the plot
sankey_plot <- gvisSankey(
  datSK,
  from = "From",
  to = "To",
  weight = "Weight",
  options = list(
    sankey = paste0("{ link: { colorMode: 'gradient'},
      node: {
        colors: ['",paste(node_color, collapse="','"), "']
           }
      }")))
# Show the plot
plot(sankey_plot)

桑基剧情

最新更新