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

Problem creating fake facet strips in ggplot2

Due to some reasons I could not use the facet feature in my real data. I have to plot every facet manually and then give each facet a strip. I was using labs(tag = "something") but the tags look less nice than facet strips. Following this answer I try to fake facet strips , by the example code:

p_list <- list()
for (i in c("lambda","mu","alpha","phi")) {
  p_list[[length(p_list) + 1]] <- ggplot2::ggplot(mtcars) +
    ggplot2::geom_point(ggplot2::aes(mpg, wt)) +
    ggplot2::geom_smooth(ggplot2::aes(mpg, wt)) +
    ggplot2::facet_wrap(~ eval(i), labeller = ggplot2::label_parsed) +
    ggplot2::labs(x = i, y = i)
}
patchwork::wrap_plots(plotlist = p_list)

Plot:

enter image description here

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

The problem is that all the fake facet strips are the same as the last one, how to fix this?

>Solution :

A solution is to create a function that builds the plot and then using lapply to iterate over the arguments (or mapply, if you want to iterate over multiple vectors), creating the plot list, that is then passed to wrap_plots:

build_plot <- function(i) {
  ggplot(mtcars) +
  geom_point(aes(mpg, wt)) +
  geom_smooth(aes(mpg, wt)) +
  facet_wrap(~ eval(i), labeller = ggplot2::label_parsed) +
  labs(x = i, y = i)
}
patchwork::wrap_plots(plotlist = lapply(c("lambda","mu","alpha","phi"), build_plot))

This would all be a lot simpler if you could just add a column to the data.frame with the label (even if it means repeating the data) and then using that column to define the facets.

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