Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically combing multiple bar plots

I'm trying to use to vertically group bar plots, sharing their x-axes.

I thought of using R's plotly's subplot for that but running into an issue I hope someone here may have a solution for.

Here are example data which have 28 groups where I'm creating a bar plot over 4 families in each group and then trying to vertically combine them using plotly::subplot:

set.seed(1)
df <- data.frame(group = paste0("G",unlist(lapply(1:28,function(i) rep(i,4)))),
                 family = paste0("F",rep(1:4,28)),
                 log2n = log2(as.integer(runif(4*28,0,30))+1),
                 stringsAsFactors = F)

Creating the list of bar plots:

library(plotly)
library(dplyr)

groups <- unique(df$group)
y.range <- c(0,max(df$log2n))
plot.list <- lapply(1:length(groups),function(g){
  group.df <- dplyr::filter(df,group == groups[g])
  plot_ly(x=group.df$family,y=group.df$log2n,type='bar',name=group.df$family,color=group.df$family,showlegend=(g==length(groups))) %>%
    layout(yaxis=list(range=y.range))
})

If I try:

plotly::subplot(plot.list,shareX=T,nrows=length(plot.list))

I get: enter image description here

So it seems like some sort of an overflow.

I gradually cut down on the number of plots in plot.list that I run subplot on and when reached 19 it seemed to stop 'overflowing':

plotly::subplot(plot.list[1:19],shareX=T,nrows=19) 

enter image description here

Any idea if there's hope to get all 28 bar plots without overflowing?

Thanks a lot

like image 343
dan Avatar asked Nov 06 '22 18:11

dan


1 Answers

I would generate the figure with ggplot and then convert it to plotly (or save it as a picture file) with proper size arguments.

library(plotly)
library(tidyverse)

g <- ggplot(df, 
       aes(x = family, y = log2n, fill = family)) +
    geom_bar(stat = 'identity') +
    facet_wrap(~group, ncol = 1) +  
    theme_minimal() + 
    theme(legend.position = "none") 

ggsave(g, file = "temp.png", width = 4, height = 40)
ggplotly(g, width = 400, height = 4000)
like image 155
amatsuo_net Avatar answered Nov 15 '22 07:11

amatsuo_net