3

I am trying to figure out how to control the order of the traces plotted in plotly, i.e. how to bring traces to the front and to the back.

Here there is a simple piece of code that plots two traces. How can I decide the order?

library(plotly)

airquality_sept <- airquality[which(airquality$Month == 9),]
airquality_sept$Date <- as.Date(paste(airquality_sept$Month, 
airquality_sept$Day, 1973, sep = "."), format = "%m.%d.%Y")

plot_ly(airquality_sept) %>%
add_trace(x = ~Date, y = ~Wind, type = 'bar', name = 'Wind',
        marker = list(color = '#C9EFF9')
       ) %>%  
add_trace(x = ~Date, y = ~Temp, type = 'scatter', mode = 'lines', name = 'Temperature', yaxis = 'y2',
        line = list(color = '#45171D')
) %>%

layout(title = 'New York Wind and Temperature Measurements for September 1973',
     xaxis = list(title = ""),
     yaxis = list(side = 'left', title = 'Wind in mph'),
     yaxis2 = list(side = 'right', overlaying = "y", title = 'Temperature in degrees F'))
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Marco De Virgilis
  • 982
  • 1
  • 9
  • 29

1 Answers1

4

The scatter trace has its y-axis set to y2 and yaxis2 in layout is overlaying y.

If you want to have the scatter trace in the background, reverse the y-axis assignment or set overlaying to y2 in yaxis.

library(plotly)

airquality_sept <- airquality[which(airquality$Month == 9),]
airquality_sept$Date <- as.Date(paste(airquality_sept$Month, 
                                      airquality_sept$Day, 1973, sep = "."), format = "%m.%d.%Y")

plot_ly(airquality_sept) %>%
  add_trace(x = ~Date, y = ~Temp, type = 'scatter', mode = 'lines', name = 'Temperature', yaxis = 'y2',
            line = list(color = '#45171D')
  ) %>%
  add_trace(x = ~Date, y = ~Wind, type = 'bar', name = 'Wind',
            marker = list(color = '#C9EFF9', opacity = 0.5)
  ) %>%
  layout(title = 'New York Wind and Temperature Measurements for September 1973',
         xaxis = list(title = ""),
         yaxis = list(side = 'left', title = 'Wind in mph', overlaying = "y2"),
         yaxis2 = list(side = 'right', title = 'Temperature in degrees F'))

enter image description here

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99