3

I would like to combine 3 plots(p1+p2+p3) together with conditional plot_layout() to p_all. However I could not get my if statement work. Could anyone guide me on this?

p3 is for sure exist, but p1|p2 might be null. layout_p is number of plot need to be bind.

{if(length(p1@data$Subject)>0) (p1)} +
{if(length(p2@data$Subject)>0) (p2)} +
p3+
{if(layout_p=3) (plot_layout(widths=c(5,5, 50)))}+
{if(layout_p=2) (plot_layout(widths=c(5, 55)))}+
{if(layout_p=1) (plot_layout(widths=c(60)))}
1
  • 1
    It's hard to tell without haveing a reproducible example. Please set it up and edit your question. For the first two conditions, wouldn't it be easier to decide based on the data? Commented Dec 4 at 14:35

1 Answer 1

2

If you want equal plot widths for any number of plots, that should be the default anyway.

To keep only plots whose data include a given variable (in your case Subject), you could, e. g.:

library(ggplot2)
library(patchwork)

p1 <- p3 <- ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot()
p2 <- ggplot(mtcars, aes(mpg, cyl)) + geom_point()


## these are the plots to keep:
plots <- list(p1, p2, p3) |> 
  Filter(f = \(p) length(p@data$Species)) ## in your case: p@data$Subject

## programmatically set plot widths (one broad, n-1 narrow):
n_narrow <- length(plots) - 1 ## number of narrow plots
small_width <- 5 ## width of narrow plots

widths <- c(rep(small_width, n_narrow),
            60 - prod(small_width, n_narrow)
            )

plots |> 
  Reduce(f = `+`) +
  plot_layout(widths = widths, 
              ## consider collecting redundant axes:
              axes = "collect" 
              )

filtered plots with collected y-axes

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answer. In fact my p1 and p2 will be a very narrow plot if they are not NULL. Is it a way to customize plot_layout()? for p1, p2 , if exist, then width=5. I updated my post to reflect this. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.