R/mk_logo.R

mk_logo = function(x, path){

  # Get unique samples
  samples = x %>% select(sample) %>% distinct %>% pull %>% sort

  # Get number of samples
  n_samples = samples %>% length

  # Set final plot width and height
  plot_width = 10
  plot_height = ceiling(n_samples/2)*3

  # Per unique id in samples, create KLD logo
  plot_list = list()
  for( id in samples ){
    # Filter to current id and 'select' columns
    #  - mut_pos        The positions which was substituted
    #  - mut_res_one    The new residue at the position
    #  - KLD_height     The calculated height of the logo-residue-letter
    # and 'spread' data from long format to wide
    PSSM_tibble = x %>%
      filter(sample == id) %>%
      select(mut_pos, mut_res_one, KLD_height) %>%
      spread(mut_res_one, KLD_height)
    # Convert to numeric matrix and set row names 1,2,...,9
    PSSM = PSSM_tibble %>% select(-mut_pos) %>% as.matrix
    rownames(PSSM) = PSSM_tibble %>% pull(mut_pos)
    # Create plot
    plot_list[[id]] = PSSM %>% t %>% ggseqlogo(method = "custom") + ggtitle(id)
  }

  # Create plot grid object for the generated plot list
  p = plot_grid(plotlist = plot_list, ncol = 2)

  # Save the plots to the user-specified path
  ggsave(filename = path, plot = p, width = plot_width, height = plot_height)

  # Done!
  return(0)
}
leonjessen/Barracoda2viz documentation built on May 28, 2019, 12:59 p.m.