1

I would like to make this kind of graph (here from Our World In data ) where the line color varies by value range.

edit : adding a screenshot to make it clearer :

enter image description here

With plotly, I found this example but working with type = scatter and mode = markers plot and not with lines:

    x <- seq(from = -2,
         to = 2,
         b = 0.1)
y <- sin(x)

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

is there any ways to use the colorRampPalette or values range but with line (actually it's a time series)

    x <- seq(from = -2,
         to = 2,
         b = 0.1)
y <- sin(x)

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

Thank you

user3355655
  • 463
  • 3
  • 15

1 Answers1

0

You can, but the more points you have the better it will look. Note that I change the .1 in x, to .001.

library(plotly)
library(RColorBrewer)

x <- seq(from = -2,
         to = 2,
         b = 0.001)
y <- sin(x)

z = cut(x, breaks = 5, include.lowest = T)

p11 <- plot_ly() %>% 
  add_lines(x = ~x,
            y = ~y,
            color = ~z,
            colors = colorRampPalette(brewer.pal(10,"Spectral"))(length(x))) %>% 
  layout(title = "Multicolored sine curve",
         xaxis = list(title = "x-axis"),
         yaxis = list(title = "y-axis"))
p11

enter image description here

If I change that .001 back to .1, it's a bit ugly! You can see the gaps.

enter image description here

Kat
  • 15,669
  • 3
  • 18
  • 51