Area chart with two colors using plotly

plotly

#1

I am trying to create a plotly area chart using r. What I have got so far is in two colors. I have two areas one for actual and one for modeled values.So if the modeled area goes above actual it should show red color and if goes down it should be green.
(eg :https://bl.ocks.org/mbostock/raw/3894205/)

Below is my code

library(dplyr)
library(plotly
        )
ab <-tibble::tribble(
  ~modeled, ~actuals, ~weekenddate,  ~err,
  501384,   481864, "2014-02-02", 19519,
  488933,   479078, "2014-02-09",  9856,
  484191,   464026, "2014-02-16", 20165,
  480443,   460339, "2014-02-23", 20104,
  482512,   464021, "2014-03-02", 18491,
  488843,   462458, "2014-03-09", 26385,
  481864,   491864, "2014-04-02", 19519,
  481864,   501864, "2014-04-09",  9856,
  464026,   480443, "2014-04-16", 20165,
  460339,   484191, "2014-04-23", 20104,
  464021,   488933, "2014-05-02", 18491,
  464021,   501384, "2014-05-09", 26385,
  501384,   481864, "2014-06-02", 19519,
  488933,   479078, "2014-06-09",  9856,
  484191,   464026, "2014-06-16", 20165,
  480443,   460339, "2014-06-23", 20104,
  482512,   464021, "2014-07-02", 18491,
  488843,   462458, "2014-07-09", 26385,
)

diff_charts <- plot_ly(x = ~ab$weekenddate, y = ~ab$modeled, type = 'scatter', mode = 'none', name = 'Modeled', fill = 'tozeroy',
                       fillcolor = 'rgba(255,0,0, 0.5)') %>%
  add_trace(x = ~ab$weekenddate, y = ~ab$actuals, name = 'Actuals', fill = 'tozeroy',
            fillcolor = 'rgba(0,255,0, 0.5)') %>%
  layout(xaxis = list(title = 'Carat'),
         yaxis = list(title = 'Density'))

diff_charts

Also how can I have the chart after a certain range to see the variations clearly.


#2

how can I have a certain range to see the variations clearly?

diff_charts %>% layout(yaxis = list(range = c(450000, 500000)))

I think this is close to what you're looking for:

plot_ly(data = ab, x = ~weekenddate) %>%
  add_ribbons(
    ymin = ~pmin(actuals, modeled), ymax = ~actuals, 
    span = I(0), color = I("green"), name = "model below actual"
  ) %>%
  add_ribbons(
    ymin = ~actuals, ymax = ~pmax(actuals, modeled), 
    span = I(0), color = I("red"), name = "model above actual"
  ) %>%
  add_lines(y = ~actuals, color = I("black"), name = "actual")