How to change node and link colors in R googleVis sankey chart

后端 未结 3 1535
醉话见心
醉话见心 2020-12-09 22:36

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


        
3条回答
  •  悲哀的现实
    2020-12-09 23:12

    I know this is older but in case anyone else is ever stuck on this - I figured out how to make the proper order and generate a string of color nodes so you can have custom colors for certain labels. Shout out to @vadym-b for the data and explaining about the order. Check it out:

    #convert to list combined of source and target for color order
    # edges is a dataframe from @vadym-b's answer above
    edges <- 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))
    
    #we have to make the order right - you need a list
    # that is a combination of From, To, From, To, From, To
    nc.df <- c()
    for (i in 1:nrow(edges)) {
      nc.df <- c(nc.df, as.character(edges$From[i]), as.character(edges$To[i]))
    }
    
    #the actualy parsing - get the unique list and return
    # colors based on what the source or target value is
    nodeColor <- sapply(unique(nc.df), function(r) {
      if (grepl('A',r)) return('red')
      if (grepl('B',r)) return('red')
      if (grepl('Z',r)) return('green')
      if (grepl('X',r)) return('green')
      if (grepl('Y',r)) return('purple')
      if (grepl('M',r)) return('blue')
      if (grepl('N',r)) return('blue')
      #return a default color if you like
      return('black')
    })
    
    #make a sankey
    library(googleVis)
    
    # put the color list in a collapsed string
    sankey <- gvisSankey(
      edges, 
      chartid = 'Sankey', 
      from="From", 
      to="To", 
      weight="Weight", 
      options=list(
        sankey = paste0("{
          iterations: 0,
          link: {
            colorMode: 'gradient'
          },
          node: {
            colors: ['",paste(nodeColor,collapse="','"),"']
          }
        }")
      )
    )
    
    plot(sankey)
    

提交回复
热议问题