更改子图的顺序

时间:2019-12-06 03:10:26

标签: r plotly

有没有办法改变R中子图的顺序?有没有办法手动更改此代码中某个因子的水平? 我想要一个在第一个图中具有权重的图,然后在其上方依次按a,b,c。但是我得到的输出是图像图中的Weight,c,a和b

这是我的代码

df<-data.frame("time"= seq(0.01,10,length.out=100),"Weight"=1:100, "a"=rnorm(100),"b"=rnorm(100),"c"=rnorm(100))

q <- df%>%
  tidyr::gather(variable, value, -time) %>%
  transform(id = as.integer(factor(variable))) %>%
  plot_ly(x = ~time, y = ~value, color = ~variable, colors = "Dark2",
          yaxis = ~paste0("y", id)
          ) %>%

 layout(
  xaxis = list(title = "Time,s",tickfont = list(size = 17),titlefont = list(size = 20)),
  yaxis = list(tickfont = list(size = 17), title="DP"),
  hoverlabel = list(font=list(size=20))
) %>% 
  add_lines() %>%
  subplot(nrows = length(df)-1, shareX = TRUE)

enter image description here

3 个答案:

答案 0 :(得分:1)

一种方法是重新排序因子级别,如下所示:

# set.seed to keep the exact same results 
set.seed(123) 
df<-data.frame("time"= seq(0.01,10,length.out=100),"Weight"=1:100, "a"=rnorm(100),"b"=rnorm(100),"c"=rnorm(100))

DF <- df%>%
  tidyr::gather(variable, value, -time) %>%
  transform(id = as.integer(factor(variable)))
DF$variable <- factor(DF$variable, levels = c("Weight", "a",  "b", "c")) #re-order 

q <- DF %>%
  plot_ly(x = ~time, y = ~value, color = ~variable, colors = "Dark2",
          yaxis = ~paste0("y", sort(id, decreasing =F))) %>% #sort the order
  layout(
    xaxis = list(title = "Time,s",tickfont = list(size = 17),titlefont = list(size = 20)),
    yaxis = list(tickfont = list(size = 17), title="DP"),
    hoverlabel = list(font=list(size=20))
  ) %>% 
  add_lines() %>%
  subplot(nrows = length(df)-1, shareX = TRUE)

q

您将需要sort(id, decreasing =F)才能获得与factor(DF$variable, levels = c("Weight", "a", "b", "c"))中设置的顺序完全相同的顺序。

enter image description here

答案 1 :(得分:0)

该问题可能是由yaxis = ~paste0("y", id)引起的。我将其替换为yaxis = ~paste0(id, "y"),以获取正确的订单。您可能需要更改一些代码以获取正确的格式。

library(plotly)
df<-data.frame("time"= seq(0.01,10,length.out=100),"Weight"=1:100, "a"=rnorm(100),"b"=rnorm(100),"c"=rnorm(100))

q <- df%>%
  tidyr::gather(variable, value, -time) %>%
  transform(id = as.integer(factor(variable))) %>%
  plot_ly(x = ~time, y = ~value, color = ~variable, colors = "Dark2",
          yaxis = ~paste0(id, "y")
  ) %>%
  layout(
    xaxis = list(title = "Time,s",tickfont = list(size = 17),titlefont = list(size = 20)),
    yaxis = list(tickfont = list(size = 17), title="DP"),
    hoverlabel = list(font=list(size=20))
  ) %>% 
  add_lines() %>%
  subplot(nrows = length(df), shareX = TRUE)
q

enter image description here

答案 2 :(得分:0)

按照以下代码交换顶部和底部子图的数据,名称和线条特征,

#assign q$x$data to one template variable p
p = q$x$data

#exchange the data, name, and line features of q$x$data[[1]] and q$x$data[[4]]
q$x$data[[1]]$x = p[[4]]$x
q$x$data[[1]]$y = p[[4]]$y
q$x$data[[1]]$name = p[[4]]$name
q$x$data[[1]]$line = p[[4]]$line

q$x$data[[4]]$x = p[[1]]$x
q$x$data[[4]]$y = p[[1]]$y
q$x$data[[4]]$name = p[[1]]$name
q$x$data[[4]]$line = p[[1]]$line

#show 
q

enter image description here