Search code examples
rcolorsdata.tableplotlyr-plotly

define color scheme when plotting line plot with plotly


I have the following data table (which is not always the same, and has always a different number of columns) and code for plotting a line chart:

dt <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                 Germany = rnorm(365, 2, 1), Austria = rnorm(365, 3, 4), 
                 Czechia = rnorm(365, 2, 3), check.names = FALSE)

colNames <- names(dt)[-1]           ## assuming date is the first column
p <- plotly::plot_ly()

for(trace in colNames){
  p <- p %>% plotly::add_trace(data = dt, x = ~date, y = as.formula(paste0("~`", trace, "`")), name = trace,
                               type = 'scatter', mode = 'lines', connectgaps = TRUE, 
                               hovertemplate = paste("%{xaxis.title.text}:  %{x}<br>",
                                                     "%{yaxis.title.text}:  %{y}<br>") )
}

p %>% 
  layout(title = "Coal",
         xaxis = list(title = "Date"),
         yaxis = list (title = "\u20ac/MWh")) 

This yields the following plot:

enter image description here

I would like to create a different color selection in different shades of green (darkest = "#007d3c", "#419F44" and lightest = "#81C07A").

How can I do this???


Solution

  • Perhaps try

    colNames <- names(dt)[-1] ## assuming date is the first column
    colors <- setNames(c("#007d3c", "#419F44", "#81C07A"), colNames)
    line_type <- setNames(c("solid", "dot", "dash"), colNames)
    p <- plotly::plot_ly()
    
    for(trace in colNames){
      p <- 
        p %>% 
        plotly::add_trace(
          data = dt, x = ~date, y = as.formula(paste0("~`", trace, "`")), name = trace,
          type = 'scatter', mode = 'lines', connectgaps = TRUE, 
          hovertemplate = paste("%{xaxis.title.text}:  %{x}<br>",
                                "%{yaxis.title.text}:  %{y}<br>"), 
          line = list(color = colors[[trace]], dash = line_type[[trace]])
        )
    }
    
    
    p %>% 
      layout(
        title = "Coal",
        xaxis = list(title = "Date"),
        yaxis = list (title = "\u20ac/MWh")
      ) 
    

    Output chart looks like this

    enter image description here

    Corrected the line_type vector as per @ismirsehregal's post