Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ggplot2: how to "wrap" a very wide plot into multiple rows

My data (multiple sequence alignment) looks like this:

rand.mat <- matrix(sample(c("A", "T", "C", "G"), size = 250 * 50, replace = T),
                   ncol = 250, nrow = 50)
rownames(rand.mat) <- paste0("gene_", 1:nrow(rand.mat))
rand.df <- rand.mat %>% reshape2::melt()

dir.create("~/test/wrap_plot/", showWarnings = F, recursive = T)
p <- rand.df %>% ggplot(aes(x = Var2, y = Var1, label = value, color = value)) + 
  geom_text(size = 2) +
  theme_bw() +
  scale_x_continuous(expand = expansion(add = 1)) +
  ggsave("~/test/wrap_plot/before_wrap.png", width = 25, height = 8)

enter image description here

It’s much wider than it’s tall. This aspect ratio needs to be maintained because readers need to be able to see each letter (I can’t squeeze the plot to make it narrower)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, to present this on a letter paper, I would like to display the second half of the plot on the next row ("wrap" the plot):
enter image description here

I wonder if there is a way to automatically wrap the plot in ggplot2? Thanks!!

>Solution :

rand.df %>% 
  mutate(half = Var2 %/% median(Var2)) %>%
  ggplot(aes(x = Var2, y = Var1, label = value, color = value)) + 
  geom_text(size = 2) +
  scale_x_continuous(expand = expansion(add = 1)) +
  facet_wrap(~half, scales = "free_x", ncol = 1) +
  theme_bw() +
  theme(strip.text = element_blank())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading