Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:The Composer of Plots
Version:1.3.2
Maintainer:Thomas Lin Pedersen <thomasp85@gmail.com>
Description: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'.
License:MIT + file LICENSE
Encoding:UTF-8
Imports:ggplot2 (≥ 3.0.0), gtable (≥ 0.3.6), grid, stats, grDevices,utils, graphics, rlang (≥ 1.0.0), cli, farver
RoxygenNote:7.3.2
URL:https://patchwork.data-imaginist.com,https://github.com/thomasp85/patchwork
BugReports:https://github.com/thomasp85/patchwork/issues
Suggests:knitr, rmarkdown, gridGraphics, gridExtra, ragg, testthat (≥2.1.0), vdiffr, covr, png, gt (≥ 0.11.0)
VignetteBuilder:knitr
Config/Needs/website:gifski
NeedsCompilation:no
Packaged:2025-08-25 08:14:43 UTC; thomas
Author:Thomas Lin PedersenORCID iD [cre, aut]
Repository:CRAN
Date/Publication:2025-08-25 10:00:02 UTC

patchwork: The Composer of Plots

Description

logo

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'.

Overview

The use and premise ofpatchwork is simple: Just addggplot2 plotstogether to compose multiplot layouts. Because of this simplicity there isnot much more to say. Still, a few functions allow you to modify thebehaviour, e.g.:

Learn more

The guides below will teach you all about what you can do with patchwork.

Author(s)

Maintainer: Thomas Lin Pedersenthomasp85@gmail.com (ORCID)

See Also

Useful links:

Examples

library(ggplot2)# You can add plots saved to variablesp1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p1 + p2# Or build it up in one stepggplot(mtcars) +  geom_point(aes(mpg, disp)) +  ggplot(mtcars) +  geom_boxplot(aes(gear, disp, group = gear))

Deprecated functions

Description

These functions are deprecated and should not be used.


Specify a plotting area in a layout

Description

This is a small helper used to specify a single area in a rectangular gridthat should contain a plot. Objects constructed witharea() can beconcatenated together withc() in order to specify multiple areas.

Usage

area(t, l, b = t, r = l)

Arguments

t,b

The top and bottom bounds of the area in the grid

l,r

The left and right bounds of the area int the grid

Details

The grid that the areas are specified in reference to enumerate rows from topto bottom, and coloumns from left to right. This means thatt andlshould always be less or equal tob andr respectively. Instead ofspecifying area placement with a combination ofarea() calls, it ispossible to instead pass in a single string

areas <- c(area(1, 1, 2, 1),           area(2, 3, 3, 3))

is equivalent to

areas < -"A##          A#B          ##B"

For an example of this, see theplot_layout() examples.

Value

Apatch_area object

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)layout <- c(  area(1, 1),  area(1, 3, 3),  area(3, 1, 3, 2))# Show the layout to make sure it looks as it shouldplot(layout)# Apply it to a patchworkp1 + p2 + p3 + plot_layout(design = layout)

Free a plot from various alignments

Description

While the purpose of patchwork is often to align plots by their various parts,sometimes this doesn't cut it and we want to compose plots without alignment.Thefree() function tells patchwork to treat the content (which can eitherbe a ggplot or a patchwork) specially and not align it with the remainingplots in the composition.free() has various modes to control what type of"non-alignment" is applied (see Details). Further you can control which sideof the plot the non-alignment is applied to. You can stackfree() calls ifyou e.g. want the top part to not align to the panel and the left part to notalign to the labels.

Usage

free(x, type = c("panel", "label", "space"), side = "trbl")

Arguments

x

A ggplot or patchwork object

type

Which type of freeing should be applied. See the Details section

side

Which side should the freeing be applied to. A string containingone or more of "t", "r", "b", and "l"

Details

free() has multiple modes depending on what you are needing:

The default"panel" will allow the panel area to ignore alginment with theremaining plots and expand as much as needed to fill any empty space.

The"label" type will instead free the axis label to keep its proximity tothe axis, even if a longer axis text from another plot would push them apart.

The"space" type also keeps axis and title together, but will instead notreserve any space for it. This allows the axis to occupy space in anotherwise empty area without making additional space available for itself.

Value

A modified version ofx with afree_plot class

Examples

# Sometimes you have a plot that defies good composition alginment, e.g. due# to long axis labelslibrary(ggplot2)p1 <- ggplot(mtcars) +  geom_bar(aes(y = factor(gear), fill = factor(gear))) +  scale_y_discrete(    "",    labels = c("3 gears are often enough",               "But, you know, 4 is a nice number",               "I would def go with 5 gears in a modern car")  )# When combined with other plots it ends up looking badp2 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p1 / p2# We can fix this be using free (here, with the default "panel" type)free(p1) / p2# If we still want the panels to be aligned to the right, we can choose to# free only the left sidefree(p1, side = "l") / p2# We can still collect guides like beforefree(p1) / p2 + plot_layout(guides = "collect")# We could use "label" to fix the layout in a different wayp1 / free(p2, "label")# Another issue is that long labels are not using already available free# space.plot_spacer() + p1 + p2 + p2# This can be fixed with the "space" typeplot_spacer() + free(p1, "space", "l") + p2 + p2

Add an area to hold collected guides

Description

Using theguides argument inplot_layout() you can collect and collapseguides from plots. By default these guides will be put on the side like withregular plots, but by adding aguide_area() to the plot you can tellpatchwork to place the guides in that area instead. If guides are notcollected or no guides exists to collect it behaves as a standardplot_spacer() instead.

Usage

guide_area()

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp, colour = factor(gear)))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)# Guides are by default kept beeside their plotp1 + p2 + p3# They can be collected and placed on the side (according to the patchwork# theme)p1 + p2 + p3 + plot_layout(guides = 'collect', ncol = 2)# Using guide_area() you can also designate an empty area for thisp1 + p2 + p3 + guide_area() + plot_layout(guides = 'collect')

Create an inset to be added on top of the previous plot

Description

The standard approach of patchwork is to place plots next to each other basedon the provided layout. However, it may sometimes be beneficial to place oneor several plots or graphic elements freely on top or below another plot. Theinset_element() function provides a way to create such insets and gives youfull control over placement.

Usage

inset_element(  p,  left,  bottom,  right,  top,  align_to = "panel",  on_top = TRUE,  clip = TRUE,  ignore_tag = FALSE)

Arguments

p

A grob, ggplot, patchwork, formula, raster, nativeRaster, or gt objectto add as an inset

left,bottom,right,top

numerics or units giving the location of theouter bounds. If given as numerics they will be converted tonpc units.

align_to

Specifies whatleft,bottom, etc should be relative to.Either'panel' (default),'plot', or'full'.

on_top

Logical. Should the inset be placed on top of the other plot orbelow (but above the background)?

clip

Logical. Should clipping be performed on the inset?

ignore_tag

Logical. Should autotagging ignore the inset?

Value

Ainset_path object

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))# Basic usep1 + inset_element(p2, 0.6, 0.6, 1, 1)# Align to the full area insteadp1 + inset_element(p2, 0, 0.6, 0.4, 1, align_to = 'full')# Grobs and other objects can be added as insets as wellp1 + inset_element(grid::circleGrob(), 0.4, 0.4, 0.6, 0.6)if (requireNamespace('png', quietly = TRUE)) {  logo <- system.file('help', 'figures', 'logo.png', package = 'patchwork')  logo <- png::readPNG(logo, native = TRUE)  p1 + inset_element(logo, 0.8, 0.8, 1, 1, align_to = 'full')}# Just as expected insets are still amenable to changes after the factp1 +  inset_element(p2, 0.6, 0.6, 1, 1) +  theme_classic()# Tagging also continues to work as expectedp1 +  inset_element(p2, 0.6, 0.6, 1, 1) +  plot_annotation(tag_levels = '1')# but can be turned off, like for wrapped plotsp1 +  inset_element(p2, 0.6, 0.6, 1, 1, ignore_tag = TRUE) +  plot_annotation(tag_levels = '1')

Align plots across multiple pages

Description

Sometimes it is necessary to make sure that separate plots are aligned, witheach other, but still exists as separate plots. That could e.g. be if theyneed to be part of a slideshow and you don't want titles and panels jumpingaround as you switch between slides. patchwork provides a range of utilitiesto achieve that. Currently it is only possible to align ggplots, but aligningpatchworks will be supported in the future.

Usage

get_dim(plot)set_dim(plot, dim)get_max_dim(...)align_patches(...)

Arguments

plot

A ggplot object

dim

A plot_dimension object as created byget_dim()

...

ggplot objects or a single list of them

Value

get_dim() andget_max_dim() return a plot_dimension object.set_dim() returns a modified ggplot object with fixed outer dimensions andalign_patches() return a list of such. The modified ggplots still behaveslike a standard ggplot and new layers, scales, etc can be added to them.

Examples

library(ggplot2)p1 <- ggplot(mtcars) +  geom_point(aes(mpg, disp)) +  ggtitle('Plot 1')p2 <- ggplot(mtcars) +  geom_boxplot(aes(gear, disp, group = gear)) +  ggtitle('Plot 2')p3 <- ggplot(mtcars) +  geom_point(aes(hp, wt, colour = mpg)) +  ggtitle('Plot 3')p4 <- ggplot(mtcars) +  geom_bar(aes(gear)) +  facet_wrap(~cyl) +  ggtitle('Plot 4')# Align a plot to p4p4_dim <- get_dim(p4)set_dim(p1, p4_dim)# Align a plot to the maximum dimensions of a list of plotsmax_dims <- get_max_dim(p1, p2, p3, p4)set_dim(p2, max_dims)# Align a list of plots with each otheraligned_plots <- align_patches(p1, p2, p3, p4)aligned_plots[[3]]# Aligned plots still behave like regular ggplotsaligned_plots[[3]] + theme_bw()

Get a grob describing the content of a patch object

Description

Methods for this generic should be defined for allpatch subclassesand should return a compliantgtable object ready to be combined withregular plot objects. In general it is best to callpatch_table() on theobject and add grobs to this aspatch_table() will return a compliantgtable

Usage

patchGrob(x, guides = "auto")

Arguments

x

Anpatch object

Value

Agtable object


Convert a patchwork to a gtable

Description

This function is the patchwork analogue ofggplot2::ggplotGrob() in that ittakes an unevaluated patchwork object and fixate it into a gtable object tofurther manipulate directly.

Usage

patchworkGrob(x)

Arguments

x

Apatchwork object

Value

Agtable object


Annotate the final patchwork

Description

The result of this function can be added to a patchwork using+ in the sameway asplot_layout(), but unlikeplot_layout() it will only have aneffect on the top level plot. As the name suggests it controls differentaspects of the annotation of the final plot, such as titles and tags. Alreadyadded annotations can be removed by setting the relevant argument toNULL.

Usage

plot_annotation(  title = waiver(),  subtitle = waiver(),  caption = waiver(),  tag_levels = waiver(),  tag_prefix = waiver(),  tag_suffix = waiver(),  tag_sep = waiver(),  theme = waiver())

Arguments

title,subtitle,caption

Text strings to use for the various plotannotations.

tag_levels

A character vector defining the enumeration format to useat each level. Possible values are'a' for lowercase letters,'A' foruppercase letters,'1' for numbers,'i' for lowercase Roman numerals, and'I' for uppercase Roman numerals. It can also be a list containingcharacter vectors defining arbitrary tag sequences. If any element in thelist is a scalar and one of'a','A','1',⁠'i⁠, or'I', this levelwill be expanded to the expected sequence.

tag_prefix,tag_suffix

Strings that should appear before or after thetag.

tag_sep

A separator between different tag levels

theme

A ggplot theme specification to use for the plot. Only elementsrelated to the titles as well as plot margin and background is used.

Details

Tagging of subplots is done automatically and following the order of theplots as they are added. When the plot contains nested layouts thetag_level argument in the nestedplot_layout will define whetherenumeration should continue as usual or add a new level. The format of thelevels are defined withtag_levels argument inplot_annotation

Value

Aplot_annotation object

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)# Add title, etc. to a patchworkp1 + p2 + plot_annotation('This is a title', caption = 'made with patchwork')# Change styling of patchwork elementsp1 + p2 +  plot_annotation(    title = 'This is a title',    caption = 'made with patchwork',    theme = theme(plot.title = element_text(size = 16))  )# Add tags to plotsp1 / (p2 | p3) +  plot_annotation(tag_levels = 'A')# Add multilevel tagging to nested layoutsp1 / ((p2 | p3) + plot_layout(tag_level = 'new')) +  plot_annotation(tag_levels = c('A', '1'))# Use a custom tag sequence (mixed with a standard one)p1 / ((p2 | p3) + plot_layout(tag_level = 'new')) +  plot_annotation(tag_levels = list(c('&', '%'), '1'))

Plot arithmetic

Description

In addition to the+ operator known inggplot2,patchwork defines logicfor some of the other operators that aids in building up your plotcomposition and reduce code-reuse.

Usage

## S3 method for class 'ggplot'e1 - e2## S3 method for class 'ggplot'e1 / e2## S3 method for class 'ggplot'e1 | e2## S3 method for class 'gg'e1 * e2## S3 method for class 'gg'e1 & e2

Arguments

e1

Aggplot orpatchwork object

e2

Aggplot orpatchwork object in case of/, or agg objectsuch as a geom or theme specification in case of* and&

Details

patchwork augment the+ operator fromggplot2 and allows the user toadd fullggplot objects together in order to compose them into the sameview. The last added plot is always the active one where new geoms etc. areadded to. Another operator that is much like it, but not quite, is-. Italso adds plots together but instead of adding the right hand side to thepatchwork defined in the left hand side, it puts the left hand side besidesthe right hand side in a patchwork. This might sound confusing, but inessence- ensures that the right and left side are put in the same nestinglevel (+ puts the right sideinto the left side). Using- might seemunintuitive if you think of the operator as "subtract", but look at it as ahyphen instead (the underlying reason is that- is the only operator in thesame precedence group as+). An alternative and more explicit way to getthe same effect as- is to usemerge() on the left hand side.

Often you are interested in creating single column or single row layouts.patchwork provides| (besides) and/ (over) operators to supportstacking and packing of plots. See the examples for their use.

In order to reduce code repetitionpatchwork provides two operators foradding ggplot elements (geoms, themes, facets, etc.) to multiple/all plots ina patchwork.* will add the element to all plots in the current nestinglevel, while& will recurse into nested patches.

Value

Apatchwork object

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)p4 <- ggplot(mtcars) + geom_bar(aes(carb))# Standard addition vs divisionp1 + p2 + p3 + plot_layout(ncol = 1)p1 + p2 - p3 + plot_layout(ncol = 1)# Stacking and packing(p1 | p2 | p3) /      p4# Add elements to the same nesting level(p1 + (p2 + p3) + p4 + plot_layout(ncol = 1)) * theme_bw()# Recurse into nested plots as well(p1 + (p2 + p3) + p4 + plot_layout(ncol = 1)) & theme_bw()

Define the grid to compose plots in

Description

To control how different plots are laid out, you need to add alayout specification. If you are nesting grids, the layout is scoped to thecurrent nesting level. An already set value can be removed by setting it toNULL.

Usage

plot_layout(  ncol = waiver(),  nrow = waiver(),  byrow = waiver(),  widths = waiver(),  heights = waiver(),  guides = waiver(),  tag_level = waiver(),  design = waiver(),  axes = waiver(),  axis_titles = axes)

Arguments

ncol,nrow

The dimensions of the grid to create - if both areNULL itwill use the same logic asfacet_wrap() to set thedimensions

byrow

Analogous tobyrow inmatrix(). IfFALSE theplots will be filled in in column-major order

widths,heights

The relative widths and heights of each column and rowin the grid. Will get repeated to match the dimensions of the grid. Thespecial value ofNA/⁠-1null⁠ will behave as⁠1null⁠ unless a fixed aspectplot is inserted in which case it will allow the dimension to expand orcontract to match the aspect ratio of the content

guides

A string specifying how guides should be treated in the layout.'collect' will collect guides below to the given nesting level, removingduplicates.'keep' will stop collection at this level and let guides beplaced alongside their plot.auto will allow guides to be collected if aupper level tries, but place them alongside the plot if not. If you modifydefault guide "position" withtheme(legend.position=...)while also collecting guides you must apply that change to the overallpatchwork (see example).

tag_level

A string ('keep' or'new') to indicate howauto-tagging should behave. Seeplot_annotation().

design

Specification of the location of areas in the layout. Can eitherbe specified as a text string or by concatenating calls toarea() together.See the examples for further information on use.

axes

A string specifying how axes should be treated.'keep' willretain all axes in individual plots.'collect' will remove duplicatedaxes when placed in the same run of rows or columns of the layout.'collect_x' and'collect_y' will remove duplicated x-axes in the columnsor duplicated y-axes in the rows respectively.

axis_titles

A string specifying how axis titltes should be treated.'keep' will retain all axis titles in individual plots.'collect' willremove duplicated titles in one direction and merge titles in the oppositedirection.'collect_x' and'collect_y' control this for x-axis titlesand y-axis titles respectively.

Value

Aplot_layout object to be added to aggassmble object

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)p4 <- ggplot(mtcars) + geom_bar(aes(carb))p5 <- ggplot(mtcars) + geom_violin(aes(cyl, mpg, group = cyl))# The plots are layed out automatically by defaultp1 + p2 + p3 + p4 + p5# Use byrow to change how the grid is filled outp1 + p2 + p3 + p4 + p5 + plot_layout(byrow = FALSE)# Change the grid dimensionsp1 + p2 + p3 + p4 + p5 + plot_layout(ncol = 2, widths = c(1, 2))# Define layout at different nesting levelsp1 +  p2 +  (p3 +     p4 +     plot_layout(ncol = 1)  ) +  p5 +  plot_layout(widths = c(2, 1))# Complex layouts can be created with the `design` argumentdesign <- c(  area(1, 1, 2),  area(1, 2, 1, 3),  area(2, 3, 3),  area(3, 1, 3, 2),  area(2, 2))p1 + p2 + p3 + p4 + p5 + plot_layout(design = design)# The same can be specified as a character string:design <- "  122  153  443"p1 + p2 + p3 + p4 + p5 + plot_layout(design = design)# When using strings to define the design `#` can be used to denote empty# areasdesign <- "  1##  123  ##3"p1 + p2 + p3 + plot_layout(design = design)# Use guides="collect" to remove duplicate guidesp6 <- ggplot(mtcars) + geom_point(aes(mpg, disp, color=cyl))p7 <- ggplot(mtcars) + geom_point(aes(mpg, hp, color=cyl))p6 + p7 + plot_layout(guides='collect')# Guide position must be applied to entire patchworkp6 + p7 + plot_layout(guides='collect') &  theme(legend.position='bottom')

Add a completely blank area

Description

This simple wrapper creates an empty transparent patch that can be added topush your other plots apart. The patch responds to addingtheme() specifications, but onlyplot.background willhave an effect.

Usage

plot_spacer()

Value

Aggplot object containing an empty plot

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p1 + plot_spacer() + p2# To have more control over spacing, you can use the `plot.margin`# parameter for `theme()` on each individual plot.(p1 + theme(plot.margin = unit(c(0,30,0,0), "pt"))) +(p2 + theme(plot.margin = unit(c(0,0,0,30), "pt")))

Wrap arbitrary graphics in a patchwork-compliant patch

Description

In order to add non-ggplot2 element to a patchwork they can beconverted to a compliant representation using thewrap_elements() function.This allows you to position either grobs, ggplot objects, patchworkobjects, or even base graphics (if passed as a formula) in either the fullarea, the full plotting area (anything between andincluding the axis label), or the panel area (only the actual area where datais drawn). Further you can still add title, subtitle, tag, and caption usingthe same approach as with normal ggplots (usingggtitle() andlabs()) as well as stylingusingtheme(). For the latter, only the theme elementstargeting plot margins and background as well as title, subtitle, etc stylingwill have an effect. If a patchwork or ggplot object is wrapped, it will befixated in its state and will no longer respond to addition of styling,geoms, etc.. When grobs and formulas are added directly, they will implicitlybe converted towrap_elements(full = x).

Usage

wrap_elements(  panel = NULL,  plot = NULL,  full = NULL,  clip = TRUE,  ignore_tag = FALSE)

Arguments

panel,plot,full

A grob, ggplot, patchwork, formula, raster,nativeRaster, or gt object to add to the respective area.

clip

Should the grobs be clipped if expanding outside its area

ignore_tag

Should tags be ignored for this patch. This is relevantwhen using automatic tagging of plots and the content of the patch does notqualify for a tag.

Value

A wrapped_patch object

Examples

library(ggplot2)library(grid)# Combine grobs with each otherwrap_elements(panel = textGrob('Here are some text')) +  wrap_elements(    panel = rectGrob(gp = gpar(fill = 'steelblue')),    full = rectGrob(gp = gpar(fill = 'goldenrod'))  )# wrapped elements can still get titles etc like ggplotswrap_elements(panel = textGrob('Here are some text')) +  wrap_elements(    panel = rectGrob(gp = gpar(fill = 'steelblue')),    full = rectGrob(gp = gpar(fill = 'goldenrod'))  ) +  ggtitle('Title for the amazing rectangles')# You can also pass in ggplots or patchworks to e.g. have it fill out the# panel areap1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p1 + wrap_elements(panel = p1 + ggtitle('Look at me shrink'))# You can even add base graphics if you pass it as a formula (requires gridGraphics package)if (requireNamespace("gridGraphics", quietly = TRUE)) {  p1 + wrap_elements(full = ~ plot(mtcars$mpg, mtcars$disp))  # Adding a grob or formula directly is equivalent to placing it in `full`  p1 + ~ plot(mtcars$mpg, mtcars$disp)}

Make a gtable created from a ggplot object patchwork compliant

Description

This function converts a gtable, as produced byggplot2::ggplotGrob() andmakes it ready to be added to a patchwork. In contrast to passingthe gtable towrap_elements(),wrap_ggplot_grob() ensures properalignment as expected. On the other hand major restructuring of the gtablewill result in an object that doesn't work properly withwrap_ggplot_grob().

Usage

wrap_ggplot_grob(x)

Arguments

x

A gtable as produced byggplot2::ggplotGrob()

Value

Atable_patch object to be added to a patchwork

Examples

library(grid)library(gtable)library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp)) + ggtitle('disp and mpg seems connected')p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))# Convert p2 so we can add new stuff to itp2_table <- ggplotGrob(p2)stamp <- textGrob('TOP SECRET', rot = 35,  gp = gpar(fontsize = 72, fontface = 'bold'))p2_table <- gtable_add_grob(p2_table, stamp,  t = 1, l = 1, b = nrow(p2_table), r = ncol(p2_table))# Adding it directly will loose alignmentp1 + p2_table# Use wrap_ggplot_grob to keep alignmentp1 + wrap_ggplot_grob(p2_table)

Wrap plots into a patchwork

Description

While the use of+ is a natural way to add plots together, it can bedifficult to string together multiple plots programmatically if the numberof plots is not known beforehand.wrap_plots makes it easy to take a listof plots and add them into one composition, along with layout specifications.

Usage

wrap_plots(  ...,  ncol = NULL,  nrow = NULL,  byrow = NULL,  widths = NULL,  heights = NULL,  guides = NULL,  tag_level = NULL,  design = NULL,  axes = NULL,  axis_titles = axes)

Arguments

...

multipleggplots or a list containingggplot objects

ncol,nrow

The dimensions of the grid to create - if both areNULL itwill use the same logic asfacet_wrap() to set thedimensions

byrow

Analogous tobyrow inmatrix(). IfFALSE theplots will be filled in in column-major order

widths,heights

The relative widths and heights of each column and rowin the grid. Will get repeated to match the dimensions of the grid. Thespecial value ofNA/⁠-1null⁠ will behave as⁠1null⁠ unless a fixed aspectplot is inserted in which case it will allow the dimension to expand orcontract to match the aspect ratio of the content

guides

A string specifying how guides should be treated in the layout.'collect' will collect guides below to the given nesting level, removingduplicates.'keep' will stop collection at this level and let guides beplaced alongside their plot.auto will allow guides to be collected if aupper level tries, but place them alongside the plot if not. If you modifydefault guide "position" withtheme(legend.position=...)while also collecting guides you must apply that change to the overallpatchwork (see example).

tag_level

A string ('keep' or'new') to indicate howauto-tagging should behave. Seeplot_annotation().

design

Specification of the location of areas in the layout. Can eitherbe specified as a text string or by concatenating calls toarea() together.See the examples for further information on use.

axes

A string specifying how axes should be treated.'keep' willretain all axes in individual plots.'collect' will remove duplicatedaxes when placed in the same run of rows or columns of the layout.'collect_x' and'collect_y' will remove duplicated x-axes in the columnsor duplicated y-axes in the rows respectively.

axis_titles

A string specifying how axis titltes should be treated.'keep' will retain all axis titles in individual plots.'collect' willremove duplicated titles in one direction and merge titles in the oppositedirection.'collect_x' and'collect_y' control this for x-axis titlesand y-axis titles respectively.

Details

Ifdesign is specified as a text stringand the plots are named (e.g.wrap_plots(A = p1, ...))and all plot names are single charactersrepresented in the design layout string, the plots will be matched to theirrespective area by name. Otherwise the areas will be filled outsequentially in the same manner as using the+ operator. See the examplesfor more.

Value

Apatchwork object

Examples

library(ggplot2)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)p4 <- ggplot(mtcars) + geom_bar(aes(carb))p5 <- ggplot(mtcars) + geom_violin(aes(cyl, mpg, group = cyl))# Either add the plots as single argumentswrap_plots(p1, p2, p3, p4, p5)# Or add them as a list...plots <- list(p1, p2, p3, p4, p5)wrap_plots(plots)# Match plots to areas by namedesign <- "#BB           AA#"wrap_plots(B = p1, A = p2, design = design)# Compare to not using named plot argumentswrap_plots(p1, p2, design = design)

Wrap a table in a patchwork compliant patch

Description

This function works much likewrap_elements() in that it turns the inputinto patchwork compliant objects that can be added to a composition. However,wrap_table() uses the knowledge that the input is a table to provide somevery nifty layout options that makes it generally better to use thanwrap_elements() for this type of object.

Usage

wrap_table(  table,  panel = c("body", "full", "rows", "cols"),  space = c("free", "free_x", "free_y", "fixed"),  ignore_tag = FALSE)

Arguments

table

A gt table or an object coercible to a data frame

panel

what portion of the table should be aligned with the panelregion?"body" means that any column and row headers will be placed outsidethe panel region, i.e. the topleft corner of the panel region will be alignedwith the topleft data cell."full" means that the whole table will beplaced inside the panel region."rows" means that all rows (including columnheaders) will be placed inside the panel region but row headers will beplaced to the left."cols" is the opposite, placing all columns within thepanel region but keeping the column header on top of it. If this is set to"body" or"cols" andspace is set to"fixed" or"free_x" then anyfootnotes or source notes in the table will be placed outside the bottom ofthe panel region.

space

How should the dimension of the table influence the finalcomposition?"fixed" means that the table width will set the width of thecolumn it occupies and the table height will set the height of the row itoccupies."free" is the opposite meaning that the table dimension will nothave any influence on the sizing."free_x" and"free_y" allows you tofree either direction while keeping the remaining fixed. Do note that if youset a specific width or height inplot_layout() it will have higherpriority than the table dimensions

ignore_tag

Should tags be ignored for this patch. This is relevantwhen using automatic tagging of plots and the content of the patch does notqualify for a tag.

Value

A wrapped_table object

Note

This functionality requires v0.11.0 or higher of the gt package

Examples

library(ggplot2)library(gt)p1 <- ggplot(airquality) +  geom_line(aes(x = Day, y = Temp, colour = month.name[Month])) +  labs(colour = "Month")table <- data.frame(  Month = month.name[5:9],  "Mean temp." = tapply(airquality$Temp, airquality$Month, mean),  "Min temp." = tapply(airquality$Temp, airquality$Month, min),  "Max temp." = tapply(airquality$Temp, airquality$Month, max))gt_tab <- gt(table, rowname_col = "Month")# Default addition usees wrap_tablep1 + gt_tab# Default places column and row headers outside panel area. Use wrap_table# to control thisp1 + wrap_table(gt_tab, panel = "full")# Tables generally have fixed dimensions and these can be used to control# the size of the area they occupyp2 <- ggplot(airquality) +  geom_boxplot(aes(y = month.name[Month], x = Temp)) +  scale_y_discrete(name = NULL, limits = month.name[9:5], guide = "none")wrap_table(gt_tab, space = "fixed") + p2

[8]ページ先頭

©2009-2025 Movatter.jp