I would like to create a Plotly graph in R that is colored green when it is positive and red when it is negative.
I attempted to do this using two separate traces producing the fist plot below which is discontinuous. I then attempted to create a colored trace using the color column which I created by the code below. These are the only implementations that I can think of using the current version of plotly.
> str(results)
'data.frame': 804 obs. of 7 variables:
$ date : Date, format: "2014-03-06" "2014-03-07" "2014-03-10" ...
$ 5yr : num 32.9 32.5 32.9 32.8 32.8 ...
$ 3y5 : num 32.4 32.1 32.5 32.4 32.4 ...
$ spread: num -0.488 -0.431 -0.438 -0.388 -0.452 ...
$ pos : num NA NA NA NA NA NA NA NA NA NA ...
$ neg : num -0.488 -0.431 -0.438 -0.388 -0.452 ...
$ color : chr "red" "red" "red" "red" ...
results$spread <- results[,3] - results[,2]
results$neg <- ifelse(results$spread < 0 , results$spread, NA)
results$pos <- ifelse(results$spread >= 0 , results$spread, NA)
plot_ly(results,
x = ~dates,
y = ~pos,
type = 'scatter',
mode = 'lines',
line = list(color = 'green')) %>%
add_trace(results,
x = ~dates,
y = ~neg,
type = 'scatter',
mode = 'lines',
line = list(color = 'red')) %>%
layout(xaxis = list(title = 'Date'),
yaxis = list(title = 'Price'))
plot_ly(results,
x = ~dates,
y = ~spread,
type = 'scatter',
mode = 'lines',
color = ~color) %>%
layout(xaxis = list(title = 'Date'),
yaxis = list(title = 'Price'))



