trace order plotly R

六眼飞鱼酱① 提交于 2019-12-02 08:26:57

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/54040078/trace-order-plotly-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!