Search code examples
r-plotlysankey-diagram

plotly r sankey add_trace


i am reading the document https://plotly.com/r/reference/sankey/, and want to change the links color for a sankey chart. But i can't quite understand the parameters in add_trace() function

where should i specify the color value?

add_trace(p,type='sankey', color=????)

enter image description here


Solution

  • You haven't provided a minimal reproducible example, so I can't jump right into your code. But I think I can point you in the right direction.

    In the documentation you screenshotted, it's saying that the color argument is one key of the list link that defines links in the plot. Using this example from the R plotly documentation for adding links, let's take a look at where that goes:

    library(plotly)
    library(rjson)
    
    json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json"
    json_data <- fromJSON(paste(readLines(json_file), collapse=""))
    
    fig <- plot_ly(
      type = "sankey",
      domain = list(
        x =  c(0,1),
        y =  c(0,1)
      ),
      orientation = "h",
      valueformat = ".0f",
      valuesuffix = "TWh",
      
      node = list(
        label = json_data$data[[1]]$node$label,
        color = json_data$data[[1]]$node$color,
        pad = 15,
        thickness = 15,
        line = list(
          color = "black",
          width = 0.5
        )
      ),
      
      link = list(
        source = json_data$data[[1]]$link$source,
        target = json_data$data[[1]]$link$target,
        value =  json_data$data[[1]]$link$value,
        label =  json_data$data[[1]]$link$label,
    
    #### Color goes here! ####
        color = "yellow"
      )
    ) 
    fig <- fig %>% layout(
      title = "Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a href='https://bost.ocks.org/mike/sankey/'>Mike Bostock</a>",
      font = list(
        size = 10
      ),
      xaxis = list(showgrid = F, zeroline = F),
      yaxis = list(showgrid = F, zeroline = F)
    )
    
    fig
    

    The plotly documentation can be a bit opaque at times. I have found it helpful to sometimes review the documentation for python. For example, this part of the python documentation does give some more guidance about changing link colors.