skip to Main Content

How can I make each new row begin with a new factor level?
Currently it wraps based on batch and sample but does not break at a new factor level of batch.
When trying ‘facet_grid(~batch~sample)’ there are many unwanted empty panels.

The results from R and the desired result from Photoshop.

enter image description here

EDITED to include smaller reproducible dataset

df <- data.frame("sample" = c("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A11"), 
                 "length_um" = c(1.8,1.9,0.52,0.75,0.14,0.95,0.84,0.46,0.25,0.13,0.31),
                 "breadth_um" = c(1.44,1.52,0.41,0.60,0.12,0.76,0.68,0.37,0.20,0.11,0.25),
                 "batch" = c("batch01","batch01","batch01","batch01","batch02","batch02","batch02","batch02","batch02","batch03","batch03"))

df <- df %>%
  mutate_if(sapply(df, is.character), as.factor)

ggplot(df, aes(x=length_um,y=breadth_um)) +
  geom_point()+
  facet_wrap(~batch~sample) 

2

Answers


  1. Try to replace facet_wrap(~batch~sample) for facet_grid(~batch~sample) .

    Login or Signup to reply.
  2. It is not possible to do it yet? The only solution I can imagine is to split dataframe by "batch" variable, and arrange the resulting multi-plot. Rewritten code from this post. I would like an integrated facet_wrap argument to do it cleaner

    library(ggplot2)
    library(cowplot)
    library(dplyr)
    
    # Sample dataframe
    df = data.frame(
      sample = c('A1','A2','A3','A4','A5','A6','A7','A8','A9','A10','A11'), 
      length_um = c(1.8,1.9,0.52,0.75,0.14,0.95,0.84,0.46,0.25,0.13,0.31),
      breadth_um = c(1.44,1.52,0.41,0.60,0.12,0.76,0.68,0.37,0.20,0.11,0.25),
      batch = c('batch01','batch01','batch01','batch01','batch02','batch02','batch02','batch02','batch02','batch03','batch03')
    )
    
    # Set factors to facet
    facet = c('batch', 'sample')
    
    # Maximum number of levels
    n_facet_max = split(df, df[[facet[1]]]) %>%
      lapply(function(x) n_distinct(x[[facet[2]]])) %>%
      unlist() %>% 
      max()
    
    # Plot function
    my_fun = function(x) {
      
      plot_tmp = ggplot(x, aes(x = length_um, y = breadth_um)) +
        geom_point()+
        facet_grid(
          x[[facet[1]]] ~ x[[facet[2]]]
        )
      
      n_facet = n_distinct(x[[facet[2]]])
      
      if (n_facet < n_facet_max) {
        plot_tmp = plot_grid(
          NULL,
          plot_tmp,
          axis = 'tb',
          ncol = 2,
          rel_widths = c(n_facet_max - n_facet, n_facet)
        )
      }
      
      return(plot_tmp)
      
    }
    
    # Plot per 'batch' variable
    plot_ls = split(df, df[[facet[1]]]) %>% lapply(function(x) my_fun(x))
    
    # Layout
    plot_grid(
      plotlist = plot_ls,
      ncol = 1,
      axis = 'r'
    )
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search