Created
August 31, 2023 23:40
-
-
Save maxdrohde/f06edb5c865f9af17d8e80d6248e50cb to your computer and use it in GitHub Desktop.
patchwork + ggtext example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(patchwork) # For composing plots | |
# See https://patchwork.data-imaginist.com/ | |
library(ggtext) # For formatting text using markdown syntax | |
# See https://wilkelab.org/ggtext/ | |
# Make a ggplot histogram from a vector of data | |
gg_hist <- function(x){ | |
data.frame(x) |> | |
ggplot() + | |
aes(x=x) + | |
geom_histogram(bins=30) | |
} | |
# Example plot using mtcars | |
p1 <- gg_hist(mtcars$mpg) + labs(title = "Plot 1") | |
p2 <- gg_hist(mtcars$wt) + labs(title = "Plot 2") | |
p3 <- gg_hist(mtcars$disp) + labs(title = "Plot 3") | |
p4 <- gg_hist(mtcars$qsec) + labs(title = "Plot 4") | |
p5 <- gg_hist(mtcars$hp) + labs(title = "Plot 5") | |
# Define a grid for the plots to be arranged using patchwork | |
layout <- " | |
AB | |
CD | |
EE | |
" | |
# patchwork syntax for arranging plots | |
my_plot <- | |
p1 + p2 + p3 + p4 + p5 + | |
plot_layout(design = layout) + | |
labs(caption = "Figure 1: This is a caption with some **bold text** using the ggtext package. Writing some more text here to show the **line-wrapping functionality** using ggtext. Making ggplots is fun!") + | |
theme( | |
plot.caption = element_textbox_simple( | |
family = "Helvetica", | |
size = 10, | |
padding = margin(5.5, 5.5, 5.5, 5.5) | |
)) | |
ggsave("myplot.png", | |
width = 8, | |
height = 10, | |
units = "in", | |
dpi = 500, | |
bg = "white") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment