pssguy pssguy - 3 months ago 68
R Question

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

Here is a toy example I have got stuck on


# 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) %>%

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

enter image description here

How can i set these up as subplots, one for each unique value of y? In the real world example, I would have 20 different y's so would ideally loop or apply the code. In addition, it would be good to set standard x scales of say c(1:10) and have, for example, 2 rows


dww dww
  1. build a list containing each of the plots
  2. set the bin sizes manually for the histograms, otherwise the automatic selection will choose different bins for each of the traces within a plot (making it look strange as in you example where the bars of each trace are different widths)
  3. use subplot to put it all together

Like this:

N = nlevels(factor(df$y))
plot_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, title=this_y)
  plot_list[[i]] = p

subplot(plot_list, nrows = 2)

enter image description here