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


here toy example have got stuck on

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 1 value of y (nb not sure why value 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 

enter image description here

how can set these subplots, 1 each unique value of y? in real world example, have 20 different y's ideally loop or apply code. in addition, set standard x scales of c(1:10) , have, example, 2 rows

tia

  1. build list containing each of plots
  2. set bin sizes manually histograms, otherwise automatic selection choose different bins each of traces within plot (making strange in example bars of each trace different widths)
  3. use subplot put together
  4. add titles individual subplots using list of annotations, explained here

like this:

n = nlevels(factor(df$y)) plot_list = vector("list", n) lab_list = vector("list", n)  (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) 

enter image description here


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -