Code Monkey home page Code Monkey logo

patchwork's Introduction

patchwork

R-CMD-check CRAN_Release_Badge CRAN_Download_Badge Codecov test coverage

The goal of patchwork is to make it ridiculously simple to combine separate ggplots into the same graphic. As such it tries to solve the same problem as gridExtra::grid.arrange() and cowplot::plot_grid but using an API that incites exploration and iteration, and scales to arbitrarily complex layouts.

Installation

You can install patchwork from CRAN using install.packages('patchwork'). Alternatively you can grab the development version from github using devtools:

# install.packages("devtools")
devtools::install_github("thomasp85/patchwork")

Basic example

The usage of patchwork is simple: just add plots together!

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + p2

patchwork provides rich support for arbitrarily complex layouts with full alignment. As an example, check out this very readable code for nesting three plots on top of a third:

p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p4 <- ggplot(mtcars) + geom_bar(aes(carb))

(p1 | p2 | p3) /
      p4

Learn more

patchwork can do so much more. Check out the guides for learning everything there is to know about all the different features:

Code of Conduct

Please note that the patchwork project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

patchwork's People

Contributors

brodieg avatar bwiernik avatar espinielli avatar ilia-kats avatar kevinushey avatar martinmspedersen avatar mhenderson avatar michaelchirico avatar olivroy avatar petehaitch avatar pettyalex avatar rmflight avatar sixvable avatar steveharoz avatar svraka avatar teunbrand avatar thomasp85 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

patchwork's Issues

Adding labels and titles to nested plots

Nice package!! Easy to use and powerful! I almost started using when I found it.

I know that it is still under development and perhaps it is already on your TODO list (and too early to jump in), but I have seen the recent addition of nested plots and I would like to know if it will be possible to name each nested plot or each plot (besides giving a title when creating it).

Something like this plot:

Many thanks for your efforts!

Plot title

Any possibility to add a title to the composite plot? If I add (+) ggtitle or labs I get the title only on the last subplot,
cheers

Using patchwork to layout plots created with facet_wrap()

It would be awesome if there was a way to use patchwork to layout subplots of a facet_wrap() ggplot.

For example, I have a set of 8 subplots that I need to show in three rows (2, 3, 3), I guess something like:

(A | B ) / (C | D | E) / (F | G | H)

But as I created the plots by ggplot(...) + facet_wrap( ~ Type), I am not sure if there is a way to use patchwork to rearrange the subplots.

Thanks!

Problems installing patchwork on Windows

I am using Windows 8.1 and R version 3.4.1. Following was my failed attempt to install patchwork:

> devtools::install_github("thomasp85/patchwork")
Downloading GitHub repo thomasp85/patchwork@master
from URL https://api.github.com/repos/thomasp85/patchwork/zipball/master
Installing patchwork
Downloading GitHub repo thomasp85/ggplot2@label-tag
from URL https://api.github.com/repos/thomasp85/ggplot2/zipball/label-tag
Installing ggplot2
Downloading GitHub repo tidyverse/rlang@master
from URL https://api.github.com/repos/tidyverse/rlang/zipball/master
Installing rlang
"C:/PROGRA~1/R/R-34~1.1/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL  \
  "C:/Users/Saba Ikhlaq/AppData/Local/Temp/Rtmp6BZPON/devtools14282f206d6/r-lib-rlang-76ad633"  \
  --library="C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4" --install-tests 

* installing *source* package 'rlang' ...
** libs

*** arch - i386
C:/RBuildTools/3.4/mingw_32/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O3 -Wall  -std=gnu99 -mtune=core2 -c capture.c -o capture.o
C:/RBuildTools/3.4/mingw_32/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O3 -Wall  -std=gnu99 -mtune=core2 -c export.c -o export.o
In file included from export/init.c:242:0,
                 from export.c:3:
export/../internal/expr-interp.h:11:20: warning: 'uq_names' defined but not used [-Wunused-variable]
 static const char* uq_names[UQ_N] = { "UQ", "!!" };
                    ^
export/../internal/expr-interp.h:12:20: warning: 'uqe_names' defined but not used [-Wunused-variable]
 static const char* uqe_names[UQE_N] = { "UQE" };
                    ^
export/../internal/expr-interp.h:19:20: warning: 'fixup_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_ops_names[FIXUP_OPS_N] = {
                    ^
export/../internal/expr-interp.h:22:20: warning: 'fixup_unary_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_unary_ops_names[FIXUP_UNARY_OPS_N] = {
                    ^
C:/RBuildTools/3.4/mingw_32/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O3 -Wall  -std=gnu99 -mtune=core2 -c internal.c -o internal.o
In file included from internal/arg.c:2:0,
                 from internal.c:1:
internal/expr-interp.h:11:20: warning: 'uq_names' defined but not used [-Wunused-variable]
 static const char* uq_names[UQ_N] = { "UQ", "!!" };
                    ^
internal/expr-interp.h:19:20: warning: 'fixup_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_ops_names[FIXUP_OPS_N] = {
                    ^
internal/expr-interp.h:22:20: warning: 'fixup_unary_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_unary_ops_names[FIXUP_UNARY_OPS_N] = {
                    ^
In file included from internal.c:4:0:
internal/expr-interp.c: In function 'call_interp_impl':
internal/expr-interp.c:318:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
C:/RBuildTools/3.4/mingw_32/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O3 -Wall  -std=gnu99 -mtune=core2 -c lib.c -o lib.o
In file included from lib.c:16:0:
lib/parse.c: In function 'r_op_as_c_string':
lib/parse.c:386:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
C:\RBuildTools\3.4\mingw_32\bin\nm.exe: lib.c: File format not recognized
C:\RBuildTools\3.4\mingw_32\bin\nm.exe: internal.c: File format not recognized
C:\RBuildTools\3.4\mingw_32\bin\nm.exe: export.c: File format not recognized
C:/RBuildTools/3.4/mingw_32/bin/gcc -shared -s -static-libgcc -o rlang.dll tmp.def capture.o export.o internal.o lib.o -Ld:/Compiler/gcc-4.9.3/local330/lib/i386 -Ld:/Compiler/gcc-4.9.3/local330/lib -LC:/PROGRA~1/R/R-34~1.1/bin/i386 -lR
installing to C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/rlang/libs/i386

*** arch - x64
C:/RBuildTools/3.4/mingw_64/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O2 -Wall  -std=gnu99 -mtune=core2 -c capture.c -o capture.o
C:/RBuildTools/3.4/mingw_64/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O2 -Wall  -std=gnu99 -mtune=core2 -c export.c -o export.o
In file included from export/init.c:242:0,
                 from export.c:3:
export/../internal/expr-interp.h:11:20: warning: 'uq_names' defined but not used [-Wunused-variable]
 static const char* uq_names[UQ_N] = { "UQ", "!!" };
                    ^
export/../internal/expr-interp.h:12:20: warning: 'uqe_names' defined but not used [-Wunused-variable]
 static const char* uqe_names[UQE_N] = { "UQE" };
                    ^
export/../internal/expr-interp.h:19:20: warning: 'fixup_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_ops_names[FIXUP_OPS_N] = {
                    ^
export/../internal/expr-interp.h:22:20: warning: 'fixup_unary_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_unary_ops_names[FIXUP_UNARY_OPS_N] = {
                    ^
C:/RBuildTools/3.4/mingw_64/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O2 -Wall  -std=gnu99 -mtune=core2 -c internal.c -o internal.o
In file included from internal/arg.c:2:0,
                 from internal.c:1:
internal/expr-interp.h:11:20: warning: 'uq_names' defined but not used [-Wunused-variable]
 static const char* uq_names[UQ_N] = { "UQ", "!!" };
                    ^
internal/expr-interp.h:19:20: warning: 'fixup_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_ops_names[FIXUP_OPS_N] = {
                    ^
internal/expr-interp.h:22:20: warning: 'fixup_unary_ops_names' defined but not used [-Wunused-variable]
 static const char* fixup_unary_ops_names[FIXUP_UNARY_OPS_N] = {
                    ^
In file included from internal.c:4:0:
internal/expr-interp.c: In function 'call_interp_impl':
internal/expr-interp.c:318:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
C:/RBuildTools/3.4/mingw_64/bin/gcc  -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I./lib/    -I"d:/Compiler/gcc-4.9.3/local330/include"     -O2 -Wall  -std=gnu99 -mtune=core2 -c lib.c -o lib.o
In file included from lib.c:16:0:
lib/parse.c: In function 'r_op_as_c_string':
lib/parse.c:386:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
C:\RBuildTools\3.4\mingw_64\bin\nm.exe: lib.c: File format not recognized
C:\RBuildTools\3.4\mingw_64\bin\nm.exe: internal.c: File format not recognized
C:\RBuildTools\3.4\mingw_64\bin\nm.exe: export.c: File format not recognized
C:/RBuildTools/3.4/mingw_64/bin/gcc -shared -s -static-libgcc -o rlang.dll tmp.def capture.o export.o internal.o lib.o -Ld:/Compiler/gcc-4.9.3/local330/lib/x64 -Ld:/Compiler/gcc-4.9.3/local330/lib -LC:/PROGRA~1/R/R-34~1.1/bin/x64 -lR
installing to C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/rlang/libs/x64
Warning in file.copy(files, dest, overwrite = TRUE) :
  problem copying .\rlang.dll to C:\Users\Saba Ikhlaq\Documents\R\win-library\3.4\rlang\libs\x64\rlang.dll: Permission denied
** R
** tests
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
*** copying figures
** building package indices
** testing if installed package can be loaded
*** arch - i386
*** arch - x64
Error: package or namespace load failed for 'rlang':
 .onLoad failed in loadNamespace() for 'rlang', details:
  call: dots_list(...)
  error: object 'rlang_dots_list' not found
Error: loading failed
Execution halted
ERROR: loading failed for 'x64'
* removing 'C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/rlang'
* restoring previous 'C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/rlang'
Warning in file.copy(lp, dirname(pkgdir), recursive = TRUE, copy.date = TRUE) :
  problem copying C:\Users\Saba Ikhlaq\Documents\R\win-library\3.4\00LOCK-r-lib-rlang-76ad633\rlang\libs\x64\rlang.dll to C:\Users\Saba Ikhlaq\Documents\R\win-library\3.4\rlang\libs\x64\rlang.dll: Permission denied
Installation failed: Command failed (1)
"C:/PROGRA~1/R/R-34~1.1/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL  \
  "C:/Users/Saba Ikhlaq/AppData/Local/Temp/Rtmp6BZPON/devtools1428690c6a70/thomasp85-ggplot2-f53b99f"  \
  --library="C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4" --install-tests 

* installing *source* package 'ggplot2' ...
** R
** data
*** moving datasets to lazyload DB
** inst
** tests
** preparing package for lazy loading
Error : 'enexprs' is not an exported object from 'namespace:rlang'
Error : unable to load R code in package 'ggplot2'
ERROR: lazy loading failed for package 'ggplot2'
* removing 'C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/ggplot2'
* restoring previous 'C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/ggplot2'
Installation failed: Command failed (1)
"C:/PROGRA~1/R/R-34~1.1/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL  \
  "C:/Users/Saba Ikhlaq/AppData/Local/Temp/Rtmp6BZPON/devtools142877ac17e4/thomasp85-patchwork-05442da"  \
  --library="C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4" --install-tests 

* installing *source* package 'patchwork' ...
** R
** preparing package for lazy loading
Error : object 'ggplot_add' is not exported by 'namespace:ggplot2'
ERROR: lazy loading failed for package 'patchwork'
* removing 'C:/Users/Saba Ikhlaq/Documents/R/win-library/3.4/patchwork'
Installation failed: Command failed (1)

I have rlang already installed. Also, I manually build the package tar ball after downloading from github and then tried installing. But again, I got Error : object 'ggplot_add' is not exported by 'namespace:ggplot2'.

Following is my sessionInfo():

> sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C                    LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] forcats_0.2.0   stringr_1.2.0   dplyr_0.7.4     purrr_0.2.4     readr_1.1.1     tidyr_0.8.0    
[7] tibble_1.4.2    ggplot2_2.2.1   tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] reshape2_1.4.3    haven_1.1.0       lattice_0.20-35   colorspace_1.3-2  yaml_2.1.14       rlang_0.1.6      
 [7] pillar_1.1.0      foreign_0.8-69    glue_1.2.0        withr_2.1.1.9000  modelr_0.1.1      readxl_1.0.0     
[13] bindrcpp_0.2      bindr_0.1         plyr_1.8.4        munsell_0.4.3     gtable_0.2.0      cellranger_1.1.0 
[19] rvest_0.3.2       devtools_1.13.2   psych_1.7.5       memoise_1.1.0     knitr_1.17        curl_2.8.1       
[25] parallel_3.4.1    broom_0.4.2       Rcpp_0.12.15      scales_0.5.0.9000 jsonlite_1.5      mnormt_1.5-5     
[31] hms_0.3           digest_0.6.15     stringi_1.1.5     grid_3.4.1        cli_1.0.0         tools_3.4.1      
[37] magrittr_1.5      lazyeval_0.2.1    crayon_1.3.4      pkgconfig_2.0.1   rsconnect_0.8.5   xml2_1.1.1       
[43] lubridate_1.7.1   assertthat_0.2.0  httr_1.3.1        rstudioapi_0.7    R6_2.2.2          git2r_0.19.0     
[49] nlme_3.1-131      compiler_3.4.1 

Error: Don't know how to add o to a plot

When ggtern is loaded

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2

Produces: Error: Don't know how to add o to a plot

Cannot arrange plots in the right order

The following example is taken from the egg package

Desired output plus labels:

image

Code:

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)")

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") +
  guides(colour = "none") +
  theme() + ggtitle("b)")

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_grid(. ~ am, scales = "free") + 
  guides(colour="none") +
  ggtitle("c)")

{p1 + {p2} + patchwork::plot_layout(ncol = 1)} +
  p3 + patchwork::plot_layout(ncol = 2)

rplot

This worked but wrong order

p3 + {
  p1 + {p2} + patchwork::plot_layout(ncol = 1)
} +
  patchwork::plot_layout(ncol = 2)

rplot01

How can I fix it? Thanks!

Remotes: missing comma and 404 error during installation

patchwork/DESCRIPTION

Lines 27 to 28 in db04895

Remotes: tidyverse/rlang
thomasp85/ggplot2:label-tag

Hi,
I tried to install the latest version with devtools but it failed, I had to specifiy an older commit.
One error is the missing comma between the remotes. I tried to fix it in a fork but then a second error popped: a 404 error on thomasp85/ggplot2:label-tag, I don't know how to fix that.

API semantics

Being more direct, patchwork's API is certainly a nice improvement over gridExtra::grid.arrange(). However, its use of + is somewhat awkward, semantically:

  • It's used to juxtapose plots, but juxtaposition is not commutative.

  • In an expression like (ggplot(...) + ...) + (ggplot(...) + ...), the + inside the parentheses and the + between the parentheses are altogether different operators. Likewise, the two +'s in the expression p1 + p2 + plot_layout(...) are completely different (the first describes the topology of the layout, whereas the second describes a rigid geometric mapping onto a plane; plot_layout() and the like might be better off applied using %>%, say).

* might be a semantically more suitable as an operator for juxtaposition, since it is conventionally noncommutative and unused in ggplot2.

On the other hand, an advantage of using + is its familiarity from ggplot2. Maybe that's a good enough reason for patchwork ... (But unless I'm mistaken, I believe the author of ggplot2 considers its use of + as a less-than-optimal design.)

plot_annotation doesn't work when combining nested levels

I was just trying to push patchwork to its limits (oh so very cool), and found that plot_annotation does not work with multiple nested levels doesn't work.

For example, using plot_annotation in the following code has no effect.

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_line(aes(mpg, disp))
p4 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p5 <- ggplot(mtcars) + geom_bar(aes(carb))


{
  {
    p1 | p2
  } / p3 + plot_layout(heights = c(1,3), tag_level = "new")
} | {
  p4 / p5 + plot_layout(heights = c(3,1))
} + plot_annotation(title = "Hello. World.", tag_levels = c("A","1"))

Not sure that this would be considered a bug per se, as I cannot think of a situation in which someone would actually want to do what I was trying to do.

Integration with ggiraph

I like the tandem of ggplot2 and ggiraph to easily create interactive plots, i.e. with tooltip features.
Is there a way to extend patchwork to allow same integration?

Feature request: Switch active plot

Loving patchwork! I would really love a way to switch the "active" plot. I can see in arithmetic.R that the last plot added is the active one, but could we have a function to switch that?

I feel like generally you'd like users to adjust things ahead of time at the ggplot2 individual plot level, but from a developer's standpoint, imagine that I wanted to make it really easy to create a multi-plot chart using patchwork. I'd return to the user a multi-plot like the one below, but then they could only adjust the bottom plot (added last) after the fact. If they could have a "switch active plot" feature then they could adjust any feature of the resulting chart. I think this could be pretty neat for maximum flexibility.

screen shot 2018-01-23 at 11 28 43 am

A reprex of what I mean

The basic idea is:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars, aes(x = cyl, y = mpg)) +
  geom_point()

p2 <- ggplot(mtcars, aes(x = as.factor(vs))) +
  geom_bar()
  
my_grouped_plot <- p1 + p2 + plot_layout(ncol = 1)

# Can access the second plot ("active")
my_grouped_plot +
  labs(title = "hello world")

# But not the first...

Created on 2018-01-23 by the reprex package (v0.1.1.9000).

Suggestion for easier vignette read

May I suggest adding headers to all the example plots (e.g. Plot 1) - in that manner it will visually be much easier to see the changes the different functionalities do.

Btw this looks so cool! Thanks!

Problems installing patchwork on R3.4.3 Mac (RStudio 1.0.153)

I have problems to install this fabulous looking package.... But I don't understand why!
Any idea?
This is copied from my console:

devtools::install_github("thomasp85/patchwork")
Downloading GitHub repo thomasp85/patchwork@master
from URL https://api.github.com/repos/thomasp85/patchwork/zipball/master
Installing patchwork
Downloading GitHub repo thomasp85/ggplot2@label-tag
from URL https://api.github.com/repos/thomasp85/ggplot2/zipball/label-tag
Installing ggplot2
trying URL 'https://cran.rstudio.com/bin/macosx/el-capitan/contrib/3.4/digest_0.6.15.tgz'
Content type 'application/x-gzip' length 161517 bytes (157 KB)
==================================================
downloaded 157 KB

Installing digest
'/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file
--no-environ --no-save --no-restore --quiet CMD INSTALL
'/private/var/folders/vh/9q9pdfhs1cbdshpq7zgzmxyc0000gn/T/RtmpOiOaGE/devtools2ca63656a78e/digest'
--library='/Library/Frameworks/R.framework/Versions/3.4/Resources/library'
--install-tests

  • installing binary package ‘digest’ ...

  • DONE (digest)
    Downloading GitHub repo hadley/scales@master
    from URL https://api.github.com/repos/hadley/scales/zipball/master
    Installation failed: Could not find build tools necessary to build scales
    Downloading GitHub repo tidyverse/rlang@master
    from URL https://api.github.com/repos/tidyverse/rlang/zipball/master
    Installation failed: Could not find build tools necessary to build rlang
    '/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file
    --no-environ --no-save --no-restore --quiet CMD INSTALL
    '/private/var/folders/vh/9q9pdfhs1cbdshpq7zgzmxyc0000gn/T/RtmpOiOaGE/devtools2ca6555bb68c/thomasp85-ggplot2-f53b99f'
    --library='/Library/Frameworks/R.framework/Versions/3.4/Resources/library'
    --install-tests

  • installing source package ‘ggplot2’ ...
    ** R
    ** data
    *** moving datasets to lazyload DB
    ** inst
    ** tests
    ** preparing package for lazy loading
    Error : 'enexprs' is not an exported object from 'namespace:rlang'
    Error : unable to load R code in package ‘ggplot2’
    ERROR: lazy loading failed for package ‘ggplot2’

  • removing ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/ggplot2’

  • restoring previous ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/ggplot2’
    Installation failed: Command failed (1)
    '/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file
    --no-environ --no-save --no-restore --quiet CMD INSTALL
    '/private/var/folders/vh/9q9pdfhs1cbdshpq7zgzmxyc0000gn/T/RtmpOiOaGE/devtools2ca66e33b40e/thomasp85-patchwork-31b2b8e'
    --library='/Library/Frameworks/R.framework/Versions/3.4/Resources/library'
    --install-tests

  • installing source package ‘patchwork’ ...
    ** R
    ** preparing package for lazy loading
    Error : object ‘ggplot_add’ is not exported by 'namespace:ggplot2'
    ERROR: lazy loading failed for package ‘patchwork’

  • removing ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/patchwork’
    Installation failed: Command failed (1)

Plots using `coord_fixed()` are not using available space

First off, great work and I started using the package almost daily!

I was wondering what are your thoughts on arranging the canvas space plots take if one of two is adjustable and the other is not.

Considering the following example:

cars = tibble::rownames_to_column(mtcars, "name")
p1 = ggplot(cars, aes(x=vs, y=name)) + geom_tile() + coord_fixed()
p2 = ggplot(cars, aes(x=disp, y=name)) + geom_point()
p1 + p2

Here, the width of p1 is defined given its height because of coord_fixed(), and the width of p2 adapts to the canvas size if plotted in isolation. (Resize plot in x and y direction to make this more obvious.)

The way patchwork currently handles this is to assume p1 and p2 will occupy half of the canvas, unless otherwise specified by plot_layout() (which I do not always know in advance).

It would be nice if there was a way to tell p2 to fill up the available space (or it would do so automatically when p1 is of fixed size).

patchwork uses non-standard versions of rlang and ggplot2?

Patchwork seems to download and compile from sources a custom version of rlang and download a custom version of ggplot2. That seems unorthodox, or maybe it's just me. A good-2-go binary of patchwork that works with the CRAN versions of the dependencies would obviously be ideal.

Using ggsave with patchwork

I love the functionality of your package, but seem to run into trouble when trying to save the created multi-plot with ggsave(). A file is created, but the figure has just a grey background.

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + p2
ggsave("figures/test.png")

I am not sure this is a permanent issue, as I have already been able to save some multi-plot figures, which were created with patchwork.

Patchwork doesn't seem to print to graphics devices

Hi, I was hoping to save some figures with patchwork today by:

p1 <- blahblah
p2 <- blahblah
png(filename = "foo.png", width = "7", height = "5", units = "in", res = "300")
p1 + p2
dev.off()

However no image is saved. The image is saved if using:

p1 <- blahblah
p2 <- blahblah
png(filename = "foo.png", width = "7", height = "5", units = "in", res = "300")
gridExtra::grid.arrange(p1, p2)
dev.off()

Failing to install patchwork

Hi Thomas,

Great thing you are doing here, but I am having a bit of trouble when I run the code to install patchwork. It says that it requires installation of additional build tools and then it is giving me an error saying that it could not find build tools necessary to build scales after I have clicked yes to install the tools. Any insight would be greatly appreciated.

Cheers,
Justin

theme property (axis.ticks) get lost

Hi Thomas,

I don't know if it's too early to open an issue, but I just encountered an issue and thought you should be notified:

In some of my plots, I shift the axis.ticks to the inside, e.g.

library(ggplot2)
library(patchwork)

my_theme <- function() {
    theme(
      axis.ticks = element_line(colour = "black"),
      axis.ticks.length = grid::unit(-0.2, "cm"),
      axis.text.x = element_text(margin = grid::unit(c(0.4,0.4,0.2,0.4), "cm")),  
      axis.text.y = element_text(margin = grid::unit(c(0.4,0.4,0.4,0.2), "cm")))
}

If I then apply this function to a ggplot2 plot, the axis ticks are shifted as expected:

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp)) + my_theme()
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear)) + my_theme()
p1

rplot

However, composing with {patchwork} removes axis.ticks:

p1 + p2

rplot01

packageVersion("patchwork")
#> [1] '0.0.1'
packageVersion("ggplot2")
#> [1] '2.2.1.9000'

[Feature Request] `labs` for created plots

Would it be possible to add a global labs function that will affect the created plot?

Title is straightforward, sometimes I have 3-4 figures and I want all of them to share one major title.
For X- and Y-axis labels, I often patchwork 4, 6, or 9 figures which have the same X- and Y-axis labels, I want to show one "big" label for each axis rather than many small labels.

Edit: As @thomasp85 points out below, plot_annotation takes care of this for the title, subtitle, and caption.

Using patchwork with ggpairs

Are there plans to get patchwork integration with ggpairs? I'm getting an error that says "Error: Don't know how to add e2 to a plot"

installation failed

I tried to intall the patchwork package, but failed, The problem is as follows,can you help me?
( the R version in my computer is 3.4.3, and the ggplot2 version is 2.2.1)

  • installing source package 'patchwork' ...
    ** R
    ** preparing package for lazy loading
    Error : object 'ggplot_add' is not exported by 'namespace:ggplot2'
    ERROR: lazy loading failed for package 'patchwork'
  • removing 'C:/Users/nyw/Documents/R/win-library/3.4/patchwork'
    In R CMD INSTALL
    Installation failed: Command failed (1)

Fixed scale coordinate systems forces aspect ratio for plot but not for axes.

Adding a fixed scale coordinate system (such as coord_equal, coord_fixed, coord_sf, coord_quickmap, etc) will correctly result in a plot with fixed aspect ratio between x and y, but the axes will preserve the device aspect ratio.

library(package = "ggplot2")
library(package = "patchwork")

ggplot(mtcars) +
    geom_point(aes(disp, mpg)) +
    coord_equal() +
        # Add plot to get an assemble (assembly?)
        ggplot(mtcars) +
        geom_point(aes(disp, mpg)) +
    patchwork::plot_layout(nrow = 1)

image

Error in FUN(X[[i]], ...) : object '.group' not found

Hello,

I'm trying to plot difference plots created from non-parametric boonet objects.

b1 <- plot(boot1, "betweenness", plot="difference", order="sample", labels=F)
b1 <- b1 + ggtitle("Correlation Network") + theme(plot.title = element_text(size = 10, face = "bold",hjust = 0.5))
b2 <- plot(boot2, "betweenness", plot="difference", order="sample", labels=F)
b2 <- b2 + ggtitle("Glasso Network") + theme(plot.title = element_text(size = 10, face = "bold", hjust = 0.5))
b3 <- plot(boot3, "betweenness", plot="difference", order="sample", labels=F) 
b3 <- b3 + ggtitle("TMFG Network") + theme(plot.title = element_text(size = 10, face = "bold", hjust = 0.5))

To get the right layout:

b1 + b2 + b3 + plot_layout(ncol = 1, heights = c(3, 1))

But get the following error

Error in FUN(X[[i]], ...) : object '.group' not found

Any help would be much appreciated. I've tried inherit.aes = FALSE as suggested on Stackoverflow but it doesn't help.

GH PR of ggplot 2405 doesnt exist

remotes::install_github("tidyverse/ggplot2#2405")
Error in github_resolve_ref.github_pull(meta$ref %||% ref, meta) : 
  Cannot find GitHub pull request tidyverse/ggplot2#2405`

Error: nrow(x) == nrow(y) is not TRUE

Hello Thomas,

Thanks again for developing this. I got the above error message while doing this:

library(ggplot2)
library(patchwork)

cdf1 <- ggplot(mtcars, aes(x = mpg, color = factor(cyl))) +
  facet_grid(am ~ .) +
  stat_ecdf(geom = "step", size = 1.0) +
  theme(aspect.ratio = 1) +
  theme(legend.position = "bottom") + guides(col = guide_legend(nrow = 1)) 
cdf1

p1 <- ggplot(mpg, aes(displ, cty)) + 
  facet_grid(drv ~ cyl) +
  geom_point()
p1

p1 + cdf1 + plot_layout(ncol = 2, widths = c(3, 1))

Any idea what went wrong?

ggplot2 is corrupt

Hi @thomasp85 ,

Thanks for this awesome package. I'm running into a bit of trouble while trying to install it though. I get the following error message when I try to load patchwork:

> library(patchwork)
Error: package or namespace load failed for ‘patchwork’ in get(Info[i, 1], envir = env):
 lazy-load database '/usr/local/lib/R/3.4/site-library/ggplot2/R/ggplot2.rdb' is corrupt
In addition: Warning message:
In get(Info[i, 1], envir = env) : internal error -3 in R_decompress1

After that, my ggplot2 becomes corrupt.

Add option to add a title to the combined plot

It'd be nice if one could add a plot title for the whole complete plot. Currently + and * add the title to the last plot only, while & adds one title per plot.

Reprex:

library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2 * ggtitle("test")
p1 + p2 & ggtitle("test")
p1 + p2 + ggtitle("test")

Extra blank plot produced in R Notebooks

When I use patchwork syntax to combine ggplot objects in an R Notebook, the resulting figure looks fine, but an extra blank plot is also generated by the chunk. This blank plot shows up in-line in the Rmd and also in the nb.html file.

Example chunk:

library(tidyverse)
library(patchwork)
data(cars)
p1 <- cars %>% 
    ggplot(aes(x = speed, y = dist)) +
    geom_point(colour = "blue")
p2 <- cars %>% 
    ggplot(aes(x = speed, y = dist)) +
    geom_point(colour = "green")
p1 + p2

... and resulting output in the notebook:
image

Here's the session info:

R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] forcats_0.2.0      stringr_1.2.0      dplyr_0.7.4        purrr_0.2.4        readr_1.1.1        tidyr_0.7.2        tibble_1.3.4      
 [8] ggplot2_2.2.1.9000 tidyverse_1.2.1    patchwork_0.0.1   

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.14      cellranger_1.1.0  compiler_3.4.1    plyr_1.8.4        bindr_0.1         tools_3.4.1       jsonlite_1.5     
 [8] lubridate_1.7.1   nlme_3.1-131      gtable_0.2.0      lattice_0.20-35   pkgconfig_2.0.1   rlang_0.1.4       psych_1.7.8      
[15] cli_1.0.0         rstudioapi_0.7    yaml_2.1.14       parallel_3.4.1    haven_1.1.0       bindrcpp_0.2      xml2_1.1.1       
[22] httr_1.3.1        knitr_1.17        hms_0.4.0         grid_3.4.1        glue_1.2.0        R6_2.2.2          readxl_1.0.0     
[29] foreign_0.8-69    modelr_0.1.1      reshape2_1.4.3    magrittr_1.5      scales_0.5.0.9000 rvest_0.3.2       assertthat_0.2.0 
[36] mnormt_1.5-5      colorspace_1.3-3  labeling_0.3      stringi_1.1.6     lazyeval_0.2.1    munsell_0.4.3     broom_0.4.3      
[43] crayon_1.3.4 

Otherwise, package is working great so far! Thanks!

Small plots with coord_quickmap()

This probably applies to other kinds of fixed ratio plots, but it seems like patchwork is leaving too much whitespace, resulting in tiny little plots.

library(ggplot2)
library(patchwork)

df <- expand.grid(x = seq(0, 360, by = 3), 
                        y = seq(-90, 0, by = 3))
df$z <- with(df, x*y)

fplot <- ggplot(df, aes(x, y, fill = z)) +
        geom_tile() +
        theme(legend.position = "bottom") +
        coord_quickmap()

fplot +
    fplot +
    plot_layout(ncol = 1)

Cowplot, on the other hand, makes a much better use of space.

cowplot::plot_grid(fplot, fplot, ncol = 1)

(Identical to gridExtra::grid.arrange(fplot(1), fplot(2), ncol = 1))

plot_spacer does not work

Running your example code:

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + plot_spacer() + p2

I get the following error message:

Error: nrow(x) == nrow(y) ist nicht TRUE

I have ggplot2 Version 2.2.1.9000 and patchwork Version 0.01 installed.

subplot title margins change when coordinates are fixed

Hi Thomas,

When making a multi-panel map plot, I discovered that the margins between the subplots and their titles changed compared to when just viewing the subplots by themselves.

Reproducible example below:

library(tidyverse)
library(broom)
library(rworldmap)
library(patchwork)

# Use country polygons for example
cntrys <- tidy(countriesCoarse)

# Plot A
pA <- ggplot(cntrys, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "#375166") +
  coord_fixed(xlim =c(-85.5,-57.4),ylim = c(9.95,30)) + # bug appears to be related to using fixed coordinates
  labs(title = "Blue map",
       subtitle = "The world is very blue") +
  theme_minimal()

# Print individual plot - title margin looks fine
pA

# Plot B
pB <- ggplot(cntrys, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "#BE2A28") +
  coord_fixed(xlim =c(-85.5,-57.4),ylim = c(9.95,30)) +
  labs(title = "Red map",
       subtitle = "The world is very red") +
  theme_minimal()

# Print multipanel plot
pA + pB + plot_layout(ncol = 1)

I believe the issue is related to using coord_fixed() - the problem goes away when this is not used and only effects the subplots that use coord_fixed()

Unable to apply wrap_elements to list of plots

Hi Thomas,

Thank you for this great package!

Related to issues #13 and #24, where you suggest implementing a wrap_grob() function, I didn't manage to find this function (maybe under development?). But both issues were closed and referenced to the commit where you have created the patchwork::wrap_elements() function. I tried this function, and it seems to work well when plotting a single grob object, but not when these are in a list. Is there any way to make this function work exactly as patchwork::wrap_plots() but for grob objects?

Thank you in advance!

Best,
Leon

Package "utf8" install causes error.

when I tried to install, this error prevented installation:

Error in download.file(url, destfile, method, mode = "wb", ...) : 
  cannot open URL 'https://cran.rstudio.com/src/contrib/utf8_1.1.2.tar.gz'
In addition: Warning message:
In download.file(url, destfile, method, mode = "wb", ...) :
  cannot open URL 'https://cran.rstudio.com/src/contrib/utf8_1.1.2.tar.gz': HTTP status was '404 Not Found'```

Feature Request: Add Plot Captions

Absolutely loving patchwork atm. Such an easy and awesome way to plot multiple graphics in a clean way. I thought it may be nice to be able to add a caption to a group of plots like Figure 3.2 and have it show up in the center beneath or above the plots much like how LaTeX can do. I'd be willing to try and add the functionality if wanted.

Add wrap_grob()

Takes a grob, a title, subtitle, and caption and makes a compliant gtable for addition etc

Panel Labeling: Feature request

First off, this is amazing - and so much more intuitive than previous tools!

One thing that comes up a lot is panel labeling - A, B, C, etc. Seems like this might be the place to add a dynamic labeling scheme so you don't have to add it to individual ggplots!

Error handling when assembling plots

I'm using patchwork to generate a multi-page PDF of assembled plots using different underlying data. Think of it as your README example

library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2

but instead of this one plot I am plotting it for n different cars.

However, not all cars have got the exact same underlying data, and some may be missing a field in their data.frame that causes ggplot to produce an error when building the subplot. An example for this is when I use facet_wrap on a variable that has no observations.

So far, I check each of these errors manually using the code:

if (class(try(ggplot_build(p1))) == "error")
    p1 = element_blank()
if (class(try(ggplot_build(p2))) == "error")
    p2 = element_blank()
# ... same for every element

This way, however, I have the build the plot twice: once for checking if it can be built, and once to actually assemble it via patchwork.

It would be nice if patchwork could handle failed plots automatically, by either leaving them empty or plot the error message instead of the panel.

One option could be to include an error handling function in plot_layout:

p1 + p2 + plot_layout(error = function(e) element_blank())
p1 + p2 + plot_layout(error = function(e)
    ggplot(data.frame(error=e), aes(x=1, y=1)) + annotate(label=e))

save as .eps does not work

Hey Thomas,

first of all - i really like patchwork, makes me spend much less time in inkscape 😛

Anyways, can you imagine why it doesn't work to save a patchwork plot as .eps?

Minimal example:

# install.packages("ggplot2")
# load package and data
options(scipen=999)  # turn-off scientific notation like 1e+48
library(ggplot2)
library(patchwork)
data("midwest", package = "ggplot2")
# midwest <- read.csv("http://goo.gl/G1K41K")  # bkup data source

# Scatterplot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
    geom_point(aes(col=state, size=popdensity)) + 
    geom_smooth(method="loess", se=F) + 
    xlim(c(0, 0.1)) + 
    ylim(c(0, 500000)) + 
    labs(subtitle="Area Vs Population", 
         y="Population", 
         x="Area", 
         title="Scatterplot", 
         caption = "Source: midwest")

p <- gg + gg

ggsave("test.eps")

... everything I get is a grey box after opening the file?

patchwork didn't work properly with these two plots

Hello,

patchwork failed to align these 2 plots together. How can I fix it? Thanks!

my_df <- structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
                               12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 
                               28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 
                               44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 
                               60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 
                               76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 
                               92, 93, 94, 95, 96, 97, 98, 99, 100), 
                        value= c(18, 9, 3, 
                        4, 3, 13, 12, 5, 8, 37, 64, 107, 11, 11, 8, 18, 5, 13, 13, 14, 
                        11, 11, 9, 14, 11, 14, 12, 10, 11, 10, 5, 3, 8, 11, 12, 11, 7, 
                        6, 6, 4, 11, 8, 14, 13, 14, 15, 10, 2, 4, 4, 8, 15, 21, 9, 5, 
                        7, 11, 6, 11, 2, 6, 16, 5, 11, 21, 33, 12, 10, 13, 33, 35, 7, 
                        7, 9, 2, 21, 32, 19, 9, 8, 3, 26, 37, 5, 6, 10, 18, 5, 70, 48, 
                        30, 10, 15, 18, 7, 4, 19, 10, 4, 32)), row.names = c(NA, 100L
                        ), class = "data.frame", .Names = c("id", "value"))

plt1 <- my_df %>% select(id, value) %>%
  ggplot() +
  geom_histogram(aes(x = value, y = (..count..)/sum(..count..)),
                 position = "identity", binwidth = 1, 
                 fill = "lightblue", color = "black") +
  ylab("Relative Frequency") +
  theme_classic()

plt2 <- my_df %>% select(value) %>%
  ggplot(aes(x = "", y = value)) +
  geom_boxplot(fill = "lightblue", color = "black") + 
  coord_flip() +
  theme_classic() +
  xlab("") +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank())

plt1 + plt2 + plot_layout(nrow = 2, heights = c(2, 1))

rplot

Adjust space between plots?

Is it possible to adjust the amount of spacing between plots? In some applications you would like wrap_plots() to act as an ordinary facet in ggplot - is it possible to collapse the white space to nothing?

Tak/Thanks!

Adding labels

Maybe I am missing it but,
Is it possible to add labels to the plots?
For example
myplot <- (p1 + p2, labels=c("A","B"))

Labelling the plots is really useful for publications and orientating the audience.

Feature request: add tableGrob() objects

Hi Thomas,

Thank you for a nice package that is build up in a very intuitive way. A feature I am missing though is the possibility to add tables as well as plots. I know you can do this with grid.arrange(), and I really miss that feature.

/Line

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.