跟踪顺序图R

时间:2019-01-04 13:39:59

标签: r plotly trace

我正在尝试弄清楚如何控制以图形方式绘制的迹线的顺序,即如何将迹线带到正面和背面。

这里有一段简单的代码绘制了两条轨迹。如何确定订单?

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 个答案:

答案 0 :(得分:2)

scatter迹线的y轴设置为y2yaxis2中的layoutoverlaying y

如果要在背景中显示scatter迹线,请反转y轴分配,或将overlaying中的y2设置为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