✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚾️ It's finally Baseball season! Root for the home team... & Register for our Sports Analytics Webinar!

Area chart with two colors using plotly

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.

You can try this code:

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

diff_chart

1 Like