rplotlycolorbrewer

R plotly marker/line color by value of other variable


How can I color a line or markers in plotly according to values of another variable. I've taken for simplicity this example.

So I would like to have x colored according the value of z. Actually, preferably with my own custom color spectral.

library(plotly)
library(RColorBrewer)

df <- data.frame(x <- seq(from = -2, to = 2, b = 0.1),
         y <- sin(x),
         z <- runif(41)
)

p11 <- plot_ly() %>% 
  add_trace(type = "scatter",
            x = ~x,
            y = ~y,
            mode = "markers",
            marker = list(size = 10,
                          color = colorRampPalette(brewer.pal(10,"Spectral"))(41))) %>% 
  layout(title = "Multicolored sine curve",
         xaxis = list(title = "x-axis"),
         yaxis = list(title = "y-axis"))
p11

Solution

  • library(plotly)
    library(RColorBrewer)
    
    set.seed(101)
    df <- data.frame(x <- seq(from = -2, to = 2, b = 0.1),
                     y <- sin(x),
                     z <- runif(41)
    )
    
    plot_ly(colors = colorRampPalette(brewer.pal(10,"Spectral"))(41)) %>% 
      add_trace(type = "scatter",
                x = ~x,
                y = ~y,
                color = ~z,
                mode = "markers",
                marker = list(size = 10)) %>% 
      layout(title = "Multicolored sine curve",
             xaxis = list(title = "x-axis", showgrid = FALSE),
             yaxis = list(title = "y-axis", showgrid = FALSE))