Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlaying scatter area in plot_ly

Tags:

r

shiny

plotly

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')
like image 336
Bartosz Stadnik Avatar asked Nov 06 '22 06:11

Bartosz Stadnik


1 Answers

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

like image 100
YBS Avatar answered Nov 12 '22 18:11

YBS