ggplot2 - How to plot a line with color vector in R Plotly -


say have following data frame:

ret <- rnorm(100, 0, 5) df <- data.frame(   x = seq(1, 100, 1),   ret = ret,   y = 100 + cumsum(ret),   col = c(ifelse(ret > 0, "red", "forestgreen"), na)[-1] ) 

here i'm simulating returns of fictional financial asset using rnorm named 'ret', , defining color vector named 'col' upticks green , downticks red.

what want produce following:

library(ggplot2) ggplot(df, aes(x=x, y=y)) + geom_line(aes(colour=col, group=1))  

enter image description here

but want make similar image using plotly can zoom in on sections of plot. first thought try using ggplotly() function around code produced desired image:

library(plotly) ggplotly(ggplot(df, aes(x=x, y=y)) + geom_line(aes(colour=col, group=1))) 

using ggplotly

but plot no longer grouped. additionally, tried using plot_ly() can't seem make line segments color according 'col' attribute i'm specifying:

plot_ly(data=df, x = ~x) %>% add_lines(y = ~y, line = list(color=~col)) 

enter image description here

but color argument doesn't affect color of line. i've tried various other things keep ending 1 of 2 undesired plots. appreciated!

note: i've made candlestick , ohlc charts plot_ly(), can't work them because y axis doesn't scale when zoom in subsection of plot.

i able desired behaviour ggplotly using geom_segment , making each segment link next (x, y) value, regardless of colour:

library(dplyr) df = df %>%     arrange(x) %>%     mutate(x_next = lead(x), y_next = lead(y))  p = ggplot(df, aes(x=x, y=y)) +      geom_segment(aes(xend = x_next, yend = y_next, colour=col)) ggplotly(p) 

that said, don't have answer why ggplotly doesn't produce desired output in first place.


Comments