5

I'd like to do plotly chart and plot filled area shape and bars on one plot. However area shape overlaying bars. I couldn't change order of elements. Is it possible to bring bars in fron?

enter image description here

data <- data.frame(years = c(2005,2006,2007), values1 = c(1,2,3), values2 = c(3,3,2))

plot_ly(data, x = data$years, y=data$values1, type = 'bar') %>% 
  add_trace(x=data$years, y=data$values2, type = 'scatter', mode = 'lines', fill = 'tozeroy')
Phil
  • 7,287
  • 3
  • 36
  • 66
  • I tried making a ggplot of this and the bars show in front of the line and area. When I try to convert it to plotly using `ggplotly`, the bars recede to the back of the area. Really weird. – csgroen Jul 16 '20 at 13:26
  • 1
    Perhaps a `layout` as shown in this link might help: https://stackoverflow.com/questions/48831856/place-plotly-bar-chart-and-box-plot-in-front-of-line-traces – YBS Jul 16 '20 at 15:00
  • Yes @csgroen, that is weird that we can't set the order of elements in easy way as for example in ggplot2. – Bartosz Stadnik Jul 17 '20 at 09:32
  • Thanks for suggestion @YBS I will check it. – Bartosz Stadnik Jul 17 '20 at 09:33

1 Answers1

1

This is adapted from the answer by @Maximilian Peters. This code

data <- data.frame(years = c(2005,2006,2007), values1 = c(1,2,3), values2 = c(3,3,2))
  
  plot_ly(data) %>%
    add_trace(x=~years, y=~values1, type = 'bar') %>%
    add_trace( x = ~years, y=~values2, type = 'scatter', mode = 'lines', fill = 'tozeroy', yaxis='y2'
    ) %>%
    layout(title = 'Trace order Plotly R',
           xaxis = list(title = ""),
           yaxis = list(side = 'left', title = 'Y - Axis', overlaying = "y2"),
           yaxis2 = list(side = 'right', title = "" )
    )

generates this output:

output

YBS
  • 19,324
  • 2
  • 9
  • 27
  • That would be very good solution, I was thinking about it, but I need to keep right side for different trace, but maybe it is possible to move second y axis to left and set the same scale for these both y axes? – Bartosz Stadnik Jul 17 '20 at 09:30
  • Yes, it is possible to create 3 y axes then set up the same scale for two left sided axes and different scale for right sided. It works fine, we can control order of elements. Thanks for your help! – Bartosz Stadnik Jul 17 '20 at 10:55