Skip to content

Instantly share code, notes, and snippets.

@davidgohel
Created September 12, 2022 13:34
Show Gist options
  • Save davidgohel/681a1783af325b290c799f237a801451 to your computer and use it in GitHub Desktop.
Save davidgohel/681a1783af325b290c799f237a801451 to your computer and use it in GitHub Desktop.
# install.packages("flextable")
library(ggplot2)
library(flextable)
library(officer)
library(patchwork)
library(magrittr)
stopifnot(packageVersion("flextable") <= numeric_version("0.8") )
gg <- ggplot(data = mtcars, aes(disp, drat)) +
geom_point(size = 4, pch = 21, color = "gray", stroke = 2) +
theme_minimal()
# r logo as png
"https://upload.wikimedia.org/wikipedia/commons/1/1b/R_logo.svg" %>%
curl::curl_download(destfile = tempfile(fileext = ".svg")) %>%
rsvg::rsvg_png(file = "r_logo.png", width = 50, height = 38)
# formatting properties for the chunks of text
fp_text_1 <- fp_text_default(font.size = 20, color = "#0097c3", bold = TRUE)
fp_text_2 <- fp_text_default(font.size = 50, color = "#CFCFAA", bold = TRUE, italic = TRUE)
fp_text_3 <- fp_text_default(font.family = "Rampart One", font.size = 40, color = "#f2af00")
fp_text_4 <- fp_text_default(vertical.align = "superscript", font.size = 20, color = "gray", italic = TRUE)
fp_text_5 <- fp_text_default(font.size = 30, font.family = "Rampart One")
# dummy long text
wrap_text <- rep("wrap ", 30) %>% paste0(collapse = "")
# the grob
ft_grob <- flextable(data.frame(dummy="")) %>%
border_remove() %>%
bg(bg = "transparent", part = "all") %>%
mk_par(part = "header", j = 1, i = 1,
value = as_paragraph(
as_image(src = "r_logo.png"),
as_image(src = "r_logo.png"),
as_image(src = "r_logo.png"),
as_image(src = "r_logo.png"),
as_chunk("This is a \nnew feature", fp_text_1),
as_chunk("(* be kind if you find some bugs!)", fp_text_4),
as_chunk("It's possible to use flextable to label ggplot, it allows", fp_text_1),
as_chunk("\ncomplex formatted text", fp_text_3),
as_chunk(" It can ", fp_text_2),
as_chunk(wrap_text, fp_text_1),
as_chunk(" and it supports '\\n'\nand can contain images", fp_text_1)
)
) %>%
mk_par(part = "body", j = 1, i = 1,
value = as_paragraph(
as_chunk("This is not a replacement for ggtext !!! It's only a toy for complex annotations", fp_text_5)
)
) %>%
flextable::width(width = 4) %>%
rotate(i=1, rotation = "btlr") %>% align(i = 1, align = "center") %>%
line_spacing(space = 2) %>%
gen_grob(fit = "auto", scaling = "full")
ragg::agg_png(filename = "annotation_fun.png", width = 10, height = 7, units = "in", res = 300)
print(
gg + inset_element(ft_grob, 0.3, .1, .9, 1)+
theme(rect = element_rect(fill="transparent"))
)
dev.off()
@davidgohel
Copy link
Author

annotation_fun

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment