Align plot areas in ggplot

前端 未结 5 1669
無奈伤痛
無奈伤痛 2020-11-29 01:04

I am trying to use grid.arrange to display multiple graphs on the same page generated by ggplot. The plots use the same x data but with different y variables. The plots come

5条回答
  •  日久生厌
    2020-11-29 01:24

    If you are using RMarkdown and knitting to PDF, I have an alternative approach. Knitr offers the functionality to plot subfigures when creating a PDF, which allows you to have multiple figures in a plot, each with their own caption.

    For this to work, each plot has to be displayed separately. By joining together several functions from the cowplot package, I made the following function which aligns plots whilst keeping them as separate objects:

    plot_grid_split <- function(..., align = "hv", axis= "tblr"){
      aligned_plots <- cowplot::align_plots(..., align=align, axis=axis)
      plots <- lapply(1:length(aligned_plots), function(x){
        cowplot::ggdraw(aligned_plots[[x]])
      })
      invisible(capture.output(plots))
    }
    

    Here is an example, comparing the layout normally vs using the function:

    ---
    output: pdf_document
    header-includes:
       - \usepackage{subfig}
    ---
    
    ```{r}
    plot_grid_split <- function(..., align = "hv", axis= "tblr"){
      aligned_plots <- cowplot::align_plots(..., align=align, axis=axis)
      plots <- lapply(1:length(aligned_plots), function(x){
        cowplot::ggdraw(aligned_plots[[x]])
      })
      invisible(capture.output(plots))
    }
    ```
    
    ```{r fig-sub, fig.cap='Four Plots Not Aligned', fig.subcap=c('Plot One', 'Plot Two', 'Plot Three', 'Plot Four'), out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}  
    library(ggplot2) 
    plot <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species)) +
      geom_point()
    
    plot + labs(title = "A nice title")
    plot + labs(caption = "A sample caption")
    plot + theme(legend.position = "none")
    plot + theme(legend.position = "top")
    ```  
    
    ```{r fig-sub-2, fig.cap='Four Plots Aligned', fig.subcap=c('Plot One', 'Plot Two', 'Plot Three', 'Plot Four'), out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}
    
    x1 <- plot + labs(title = "A nice title")
    x2 <- plot + labs(caption = "A sample caption")
    x3 <- plot + theme(legend.position = "none")
    x4 <- plot + theme(legend.position = "top")
    
    plot_grid_split(x1, x2, x3, x4)
    ```
    

    • You can learn more about subfigures in R within this post.
    • In addition, you can check out the knitr options to read more about the chunk options for subfigures: https://yihui.name/knitr/options/

提交回复
热议问题