我如何使用 R 在 plotly 中创建子图,其中每个子图是两条轨迹

How can I create subplots in plotly using R where each subplot is two traces

这是我卡住的玩具示例

library(plotly)
library(dplyr)

# construct data.frame
df <- tibble(x=c(3,2,3,5,5,5,2),y=c("a","a","a","b","b","b","b"))

# construct data.frame of last y values
  latest <- df %>% 
   group_by(y) %>% 
   slice(n())

# plot for one value of y (NB not sure why value for 3 appears?)
  p <- plot_ly() %>% 
   add_histogram(data=subset(df,y=="b"),x= ~x) %>%   
  add_histogram(data=subset(latest,y=="b"),x= ~x,marker=list(color="red")) %>%
  layout(barmode="overlay",showlegend=FALSE,title= ~y)
  p

我如何将它们设置为子图,一个对应 y 的每个唯一值?在现实世界的例子中,我会有 20 个不同的 y,所以理想情况下会循环或应用代码。此外,最好设置 c(1:10) 的标准 x 比例,例如,2 行

TIA

  1. 构建一个包含每个地块的列表
  2. 为直方图手动设置 bin 大小,否则自动选择将为图中的每个轨迹选择不同的 bin(让它看起来很奇怪,就像你的例子中每条轨迹的条宽度不同)
  3. 使用子图将它们放在一起
  4. 使用注释列表为各个子图添加标题,如解释的那样here

像这样:

N = nlevels(factor(df$y))
plot_list = vector("list", N)
lab_list = vector("list", N)

for (i in 1:N) {
  this_y = levels(factor(df$y))[i]
  p <- plot_ly() %>% 
    add_trace(type="histogram", data=subset(df,y==this_y), x=x, marker=list(color="blue"),
              autobinx=F, xbins=list(start=0.5, end=6.5, size=1)) %>%   
    add_trace(type="histogram", data=subset(latest,y==this_y), x = x, marker=list(color="red"), 
              autobinx=F, xbins=list(start=0.5, end=6.5, size=1)) %>%
    layout(barmode="overlay", showlegend=FALSE)
  plot_list[[i]] = p

  titlex = 0.5
  titley = c(1.05, 0.45)[i]
  lab_list[[i]] = list(x=titlex, y=titley, text=this_y, 
                       showarrow=F, xref='paper', yref='paper', font=list(size=18))
}

subplot(plot_list, nrows = 2) %>%
  layout(annotations = lab_list)