International College of Digital Innovation, CMU
October 29, 2025
The patchwork package is the one extension of ggplot2 package.
The goal of patchwork package is to make it ridiculously simple to combine separate ggplots into the same graphic.
How to in install
How to use their package
viewof layoutType = Inputs.radio(
[
"Side-by-side (p1 | p2)",
"Stacked (p1 / p2)",
"2x2 grid ((p1|p2)/(p3|p4))",
"Custom: columns & ratios",
"Custom: rows & ratios",
"Design string",
"With spacer",
"Collect legends + tags"
],
{ label: "patchwork layout", value: "Side-by-side (p1 | p2)", inline: false }
)
viewof ncolVal = Inputs.range([1, 4], { value: 2, step: 1, label: "ncol (custom columns)" })
viewof nrowVal = Inputs.range([1, 4], { value: 2, step: 1, label: "nrow (custom rows)" })
viewof widthsTxt = Inputs.text({ label: "widths (comma-separated)", value: "2,1" })
viewof heightsTxt= Inputs.text({ label: "heights (comma-separated)", value: "1,2" })
// ตัวอย่าง design: แทนกริด 2x2 ด้วยตัวอักษร
// "AB\nCD" หมายถึง ช่องบนซ้าย=A, บนขวา=B, ล่างซ้าย=C, ล่างขวา=D
viewof designTxt = Inputs.textarea({ label: "Design string (e.g. 'AB\nCD')", value: "AB\nCD", rows: 3 })
viewof collectGuides = Inputs.toggle({label: "guides = 'collect' ?", value: false})
viewof tagLevel = Inputs.select(["none","A","1","a","i"], { label: "tag_levels", value: "none" })
viewof showCode = Inputs.toggle({label: "Show R code used?", value: true})From mtcars data set
We can use \(+\) to add plots together in the same row (up to three plots).
We can use \(/\) to add plots together in the same column.
We can mix the plots with multiple rows and columns.
We can control by using this command
As plots will always be added to the patchwork on the left-hand side, it is not possible to nest the left-hand side beside the right-hand side with the standard operators shown above.
As plots will always be added to the patchwork on the right-hand side, it is not possible to nest the left-hand side beside the right-hand side with the standard operators shown above.
Often, especially when it comes to theming, you want to modify everything at once. patchwork provides two additional operators that facilitates this.
& will add the element to all subplots in the patchwork.
* will add the element to all the subplots in the current nesting level.
Titles, subtitles and captions
One of the most needed things is to add descriptive text to your plot ensemble. To achieve this, you simply add it to your patchwork using plot_annotation()
Input
viewof chartType = Inputs.radio(
["Scatter", "Bar", "Box", "Line", "Heatmap"],
{ label: "Chart Type", value: "Scatter", inline: true }
)
// เลือกชุดข้อมูล (ไม่มี diamonds, ไม่มี native plotly)
viewof datasetName = Inputs.select(
["mtcars", "iris", "mpg", "economics"],
{ label: "Dataset", value: "mtcars" }
)
// เลือกการทำ color mapping
viewof colorAes = Inputs.radio(
["None", "Category", "Numeric"],
{ label: "Color mapping", value: "Category", inline: true }
)