Si alguien está buscando una manera fácil de etiquetar facetas para informes o publicaciones, el paquete egg
( CRAN ) tiene funciones tag_facet()
y tag_facet_outside()
funciones bastante ingeniosas .
library(ggplot2)
p <- ggplot(mtcars, aes(qsec, mpg)) +
geom_point() +
facet_grid(. ~ am) +
theme_bw(base_size = 12)
# install.packages('egg', dependencies = TRUE)
library(egg)
Etiqueta dentro
Defecto
tag_facet(p)
Nota: si desea conservar el texto y el fondo de la tira, intente agregar strip.text
ystrip.background
volver a theme
ingresar o eliminar theme(strip.text = element_blank(), strip.background = element_blank())
de la tag_facet()
función original .
tag_facet <- function(p, open = "(", close = ")", tag_pool = letters, x = -Inf, y = Inf,
hjust = -0.5, vjust = 1.5, fontface = 2, family = "", ...) {
gb <- ggplot_build(p)
lay <- gb$layout$layout
tags <- cbind(lay, label = paste0(open, tag_pool[lay$PANEL], close), x = x, y = y)
p + geom_text(data = tags, aes_string(x = "x", y = "y", label = "label"), ..., hjust = hjust,
vjust = vjust, fontface = fontface, family = family, inherit.aes = FALSE)
}
Alinear arriba a la derecha y usar números romanos
tag_facet(p, x = Inf, y = Inf,
hjust = 1.5,
tag_pool = as.roman(1:nlevels(factor(mtcars$am))))
Alinee la esquina inferior izquierda y use letras mayúsculas
tag_facet(p,
x = -Inf, y = -Inf,
vjust = -1,
open = "", close = ")",
tag_pool = LETTERS)
Define tus propias etiquetas
my_tag <- c("i) 4 cylinders", "ii) 6 cyls")
tag_facet(p,
x = -Inf, y = -Inf,
vjust = -1, hjust = -0.25,
open = "", close = "",
fontface = 4,
size = 5,
family = "serif",
tag_pool = my_tag)
Etiqueta afuera
p2 <- ggplot(mtcars, aes(qsec, mpg)) +
geom_point() +
facet_grid(cyl ~ am, switch = 'y') +
theme_bw(base_size = 12) +
theme(strip.placement = 'outside')
tag_facet_outside(p2)
Editar : agregar otra alternativa usando el paquete stickylabeller
- `.n` numbers the facets numerically: `"1"`, `"2"`, `"3"`...
- `.l` numbers the facets using lowercase letters: `"a"`, `"b"`, `"c"`...
- `.L` numbers the facets using uppercase letters: `"A"`, `"B"`, `"C"`...
- `.r` numbers the facets using lowercase Roman numerals: `"i"`, `"ii"`, `"iii"`...
- `.R` numbers the facets using uppercase Roman numerals: `"I"`, `"II"`, `"III"`...
# devtools::install_github("rensa/stickylabeller")
library(stickylabeller)
ggplot(mtcars, aes(qsec, mpg)) +
geom_point() +
facet_wrap(. ~ am,
labeller = label_glue('({.l}) am = {am}')) +
theme_bw(base_size = 12)
Creado por el paquete reprex (v0.2.1)