The Composer of Plots

The 'ggplot2' package provides a strong API for sequentially building up a plot, but does not concern itself with composition of multiple plots. 'patchwork' is a package that expands the API to allow for arbitrarily complex composition of plots by, among others, providing mathematical operators for combining multiple plots. Other packages that try to address this need (but with a different approach) are 'gridExtra' and 'cowplot'.


patchwork

R-CMD-check CRAN_Release_Badge CRAN_Download_Badge Codecov testcoverage

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.

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.

install.packages("patchwork")

1.3.2 by Thomas Lin Pedersen, a year ago


https://patchwork.data-imaginist.com, https://github.com/thomasp85/patchwork


Report a bug at https://github.com/thomasp85/patchwork/issues


Browse source code at https://github.com/cran/patchwork


Authors: Thomas Lin Pedersen [cre, aut] (ORCID:


Documentation:   PDF Manual  


MIT + file LICENSE license


Imports ggplot2, gtable, grid, stats, grDevices, utils, graphics, rlang, cli, farver

Suggests knitr, rmarkdown, gridGraphics, gridExtra, ragg, testthat, vdiffr, covr, png, gt


Imported by AIGENIE, AgeBandDecomposition, Analitica, AnanseSeurat, AntsNet, AssumpSure, BOP2FE, BasicStatsPlots, BayesFBHborrow, BayesPower, BayesSIM, BioGSP, CLRtools, CRABS, CarletonStats, CellWindX, ChemoSpec, CimpleG, CoSMoS, ComplexUpset, Coxmos, CytOpT, DEplotting, DamageDetective, E2E, ENMeval, EcoCleanR, Entropic.Scree, EpiForsk, EpiNow2, EvoPhylo, FESta, FPScausal, FishDiveR, FluxSeparator, G2Sd, GPvam, GrowthCurveME, HYPEtools, HaploCatcher, InterconectaR, LCPA, LMD, LSTS, LipidMS, LongDat, LongDecompHE, MAIHDA, MF.beta4, MLwrap, MetaEntropy, MixMashNet, MultiSEp, NBvarsel, NetworkChange, NetworkExtinction, OmicFlow, OptSurvCutR, OrgHeatmap, PRECAST, PopPsiSeqR, RARfreq, RNAseqQC, RSP, RadEro, RandomWalker, Rbearcat, RepeatedHighDim, Robyn, RougeLM, SCoRES, SEIRfansy, SPARRAfairness, Saylac, SeaVal, SepTest, SerolyzeR, Seurat, ShiftHappens, Signac, SimplyAgree, SlimR, SlotLim, SouthParkRshiny, SpaCCI, Spectran, SppTrend, StabilityApp, StreamCatTools, SuperCell, SurprisalAnalysis, Sysrecon, TidyDensity, Tivy, TwoCutoff, TwoStepSDFM, VARcheck, WMFM, XYomics, Xplortext, activAnalyzer, agriReg, ale, alphavantagepf, aplot, autoReg, autograph, autostats, avstrat, badp, bartMan, bayesTLS, bayesics, besthr, bfbin2arm, biometryassist, blockr.ggplot, bml, boiwsa, brinton, bspcov, calmr, caretEnsemble, celliverse, chillR, cia, cifmodeling, circhelp, citcdf, climatehealth, codyna, confMeta, crosshap, csbewma, csemTools, ctsmTMB, dartR, dartR.base, dartR.captive, dartR.popgen, dartR.sexlinked, dataquieR, dcvar, decisionSupport, depictr, dgpsi, dicepro, diy.sem.plot, dotwhisker, dppca, duet, dynamite, dyngen, eVCGsampler, ecic, edar, effectplots, ern, erplots, eudract, eyeris, fairmodels, fdaPOIFD, ffaframework, figpatch, fitbitViz, foqat, forestsearch, foresty, funcharts, funkyheatmap, gammaFuncModel, gcemod, gdverse, geohabnet, gg1d, ggEDA, ggRandomForests, ggadjustedforest, ggbrain, ggbreak, ggcharts, ggforestplotR, gglm, ggmRSCU, ggpicrust2, ggquickeda, ggrecipes, ggreveal, ggseqplot, ggstats, ggstatsplot, ggstratify, ggsurvfit, gosset, grafify, grandR, gratia, greatR, greenR, growthTrendR, gsaot, gtregression, guideR, hahmmr, harbinger, hhmR, hierarchicalSets, hlrhotrix, hockeystick, iNZightTS, idopNetwork, iglu, infer, inough, insane, insetplot, insurancerating, int3ract, interpretCI, intradayModel, investlabr, ivDiag, ivd, ivolcano, janusplot, jskm, kollaR, lactater, lame, lares, loon.ggplot, mFD, mSigPlot, maraca, markstat, mcp, mectx, messi, metabolic, metainsight, metan, mispitools, mlr3shiny, modgo, movedesign, mrIML, mrgsim.sa, multimedia, multiplestressR, munch, mvgam, myTAI, netDFI, neuralGAM, neuroim2, numbat, oRaklE, openair, ordPanel, packageRank, pctax, pcvr, pep725, plotlsirm, plotthis, pmartR, powerly, ppseq, puff, qbinplots, qbrms, quollr, r6qualitytools, rACMEMEEV, radiant.basics, radiant.data, radiant.model, radiant.multivariate, rambur, randotools, rbiom, rcssci, reappraised, redist, resourcecode, retmort, rhierbaps, rnaCrosslinkOO, rupturesRcpp, sae4health, scCustomize, scGate, scPairs, scRNAstat, scistreer, see, semboottools, seqHMM, serocalculator, serosv, sfclust, sffdr, shadowVIMP, shapviz, shinyMixR, shinySbm, shinymrp, skytrackr, smplot2, spacemodR, spatialRF, speccurvieR, splithalf, spotoroo, starvz, stepssurvey, sulcimap, sumvar, survex, sysAgNPs, tRigon, teal.modules.general, thisplot, tidyGenR, tidyHeatmap, tidypopgen, tidyposterior, tidysdm, tinyarray, tooth, topics, toxSummary, trackeR, traumar, treefit, triptych, upset.hp, uteals, vDiveR, vacalibration, vennDiagramLab, vimixr, vismi, visvaR, visxhclust, vital, wdiexplorer, whippr, xaiHydro, xiacf, xplaineff.

Depended on by MixOptim, SimpleUpset, immunarch, nzilbb.vowels, pmxTools.

Suggested by AMISforInfectiousDiseases, ARUtools, AlleleShift, BKBreed, BKMutate, BKQualit, BayesERtools, BayesianReasoning, CNVreg, Canek, CaseBasedReasoning, CausalSpline, CharAnalysis, ChemoSpecUtils, ClustAssess, CohortSurvival, ConfidenceEllipse, CytoSimplex, DMAR, DSIR, DecisionDrift, EDCimport, EpiNova, FAVA, FAVAR, FLORAL, FuzzySpec, GET, GIFT, Guerry, HRRI, HVT, IBLM, IOBR, IncidencePrevalence, JSmediation, LightLogR, LorMe, MASSExtra, MRG, MassWateR, MedLEA, MiscMetabar, MorphoRegions, MultiSpline, MyoScore, NMsim, OBIC, PKbioanalysis, PathwaySpace, PatientProfiles, PoweREST, PsyMetricTools, RGraphSpace, Rclade, RegimeChange, Ruido, SCpubr, SPIChanges, SSIMmap, SUMMER, SeuratExplorer, SignalY, SimNPH, SuperSurv, TRexSelector, TextAnalysisR, USPopulationSampler, Upsilon, VeraCrop, VizTest, accrualPlot, admixr2, ameras, amp.dm, appac, appeears, apsimeval, ascent, autocodebook, bage, bayesplot, bayestestR, bayprior, bbknnR, beezdemand, bidser, bild, biomod2, bootkmeans, brand.yml, broom.helpers, bsitar, camcorder, camtrapR, canaper, canvasXpress, censusindia, cgam, chem16S, chessboard, chomper, climateBR, climniche, clugenr, colleyRstats, contagionchannels, coveffectsplot, cowplot, cricketdata, cubble, decisionpaths, delimtools, dscore, duckspatial, easyRasch2, easyRaschBayes, easybio, easystats, ecorisk, epidist, epmfd, ernest, fahb, fastml, faux, ferrn, fftab, fishmechr, fivethirtyeight, fjohansen, flextable, fmesher, fonctionr, forestecology, forestly, fractalforest, funbiogeo, funtimes, geneticae, geofi, geslaR, ggDoE, ggHoriPlot, ggalttext, ggblanket, ggcube, ggdibbler, ggdist, ggeasy, ggeffects, ggformula, gggenomes, ggguides, gghinton, ggkodom, gglyph, ggmeta, ggmice, ggmosaic2, ggpedigree, ggplotify, ggplotplus, ggpop, ggprism, ggrefine, ggrepel, ggridges, ggsketch, ggtintshade, ggwidth, goldfish, grassr, growR, gspcr, harmony, hatchR, heplots, hermiter, hilldiv3, hmde, ibdsim2, iml, industRial, inferCSN, infoelectoral, inlabru, ipd, ipeaplot, jlmerclusterperm, kumquat, lande, likelihoodTools, lionfish, lisat, lmls, lterdatasampler, maidr, mapindia, marginaleffects, marqLevAlg, marquee, masc, mascarade, matrixset, mccount, metaconfoundr, mfp2, misty, mlmoderator, mlr3fairness, mlr3spatiotempcv, mlr3viz, modelbased, modeldiagramR, moderndive, mpmsim, mrddGlobal, msmtools, multifunc, mvinfluence, netify, neuroSCC, nichetools, nn2poly, nuggets, oda, orchaRd, pacu, painbow, palettes, paramix, partR2, performance, plotmm, plotscaper, portvine, power.nb, ppforest2, prakriti, prcbench, precrec, pressfreedom.data, preventr, pridit, projoint, proxymix, pvLRT, quarto, quartose, qviewparsR, r4ds.tutorials, r4pde, r5r, rTPC, rarefun, rbmiUtils, reaborn, regressinator, rempsyc, reporter, reservr, rmcorr, robber, rredlist, rxode2, scatterbar, searchAnalyzeR, segregation, sfdep, shewhartr, shrinkr, sigminer, simdata, singleCellHaystack, sitrep, socialdrift, spFFBS, spStack, spatialkit, specProc, spinifex, ssdtools, sshist, starling, statim, survalis, surveyPrev, tabnet, taylor, tbl.now, testflow, tfrmt, tidychangepoint, tidypaleo, tinythemes, tlars, trending, trialSizing, tseffects, tulpa, unityForest, unusualprofile, vayr, vroom, whitewater, wmwAUC, x3ptools, xaci, xplainfi.

Enhanced by ggalign.


See at CRAN