简体   繁体   中英

trace order plotly R

I am trying to figure out how to control the order of the traces plotted in plotly, ie 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'))

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'))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM