0

i'm working on R and i just made a plot. The thing is that i need to fill in the area between two traces but not all along the range.
I found the arguments fill="...." but it fills all plots and i need to control between which trace i fill in area and to set a range shorter than the plot range.
So can you please help me to do it ?

       A=c(0,1,2,3,4,5,6,5,4,3,2,1,0)
       B=rep(3,13)
       sem=c(0:12)
       p <- plot_ly(data, x = sem[order(sem)], 
       y = A,name = 'A', type = 'scatter',
       mode = 'lines') %>%
       add_trace(y = B,name = 'B', 
       mode = 'lines+markers') %>%
       layout(title = sprintf("Effect",         
       font=list(
       family = "arial",
       size = 12,
       color = 'black'),
     yaxis = list(zeroline = FALSE,title="Weight(T)"),        
     xaxis = list(range=c(-10:25),zeroline = FALSE,title="week"),
     legend=list(
     font = list(
       family = "sans-serif",
       size = 12,
       color = "#000"),
       bgcolor = "#E2E2E2",
       bordercolor = "#FFFFFF",
       borderwidth = 2))

This is what i'm trying to do

Orhan Yazar
  • 909
  • 7
  • 19

1 Answers1

0

I'm not that familiar with the plot_ly syntax of shading. Here's an alternative with ggplot instead:

ggplot(data, aes(x=sem)) + 
      geom_line(aes(y = A)) + 
      geom_line(aes(y = B)) +
      geom_ribbon(data=subset(data, 3 <=  sem & sem <= 9), 
                  aes(ymin=B, ymax= A), fill="blue", alpha="0.5")

enter image description here

Adam Quek
  • 6,973
  • 1
  • 17
  • 23
  • First, thanks for your answer Adam. Do you thinks that i can do the same with ggplot2 and if yes, maybe i can use the same way to do it with plotly. – Orhan Yazar Apr 25 '17 at 12:01
  • also, im getting this error when i try your code: Error in `*tmp*` + geom_line(aes(y = B)) : non-numeric argument to binary operator – Orhan Yazar Apr 25 '17 at 12:29
  • Since the syntax of `data` wasn't given in your post, I assumed: `data <- data.frame(A,B,sem)`. I just ran on a clean copy R of with that data and the ggplot code above and it gave me back the same plot. Can you try it again? Make sure you have `ggplot2` installed and loaded before running. – Adam Quek Apr 25 '17 at 15:17
  • Yes it's ok it works now. And for information i managed to do it with plotly: `p <- ggplot(data, aes(x=sem)) + geom_line(aes(y = A)) + geom_line(aes(y = B)) + geom_ribbon(data=subset(data, 3 <= sem & sem <= 9), aes(ymin=B, ymax= A), fill="blue") ggplotly(p)` – Orhan Yazar Apr 26 '17 at 10:00
  • Thank you very much Adam – Orhan Yazar Apr 26 '17 at 10:02