I want to mutate a column that has formatted facet titles that I can then use in a ggplot
with facet_wrap
. I know that I need to use plotmath and maybe bquote, but I am unable to get all of the components working together to produce the desired output. I have tried a lot of combinations of bquote and atop, as well as using ~
and .()
and pasting things together, but no luck. I know that you can also use grob
, but the output is in a knitted .Rmd. I also would like to make the top title larger if possible.
Reproducible Example
library(ggplot2)
library(dplyr)
mpg_df <- mpg %>%
select(year, manufacturer, model, cty, hwy) %>%
filter(
year == 1999 & manufacturer == "audi" & model == "a4 quattro" |
year == 2008 &
manufacturer == "dodge" & model == "ram 1500 pickup 4wd"
) %>%
mutate(
title = paste0(
"bold('This is the manufacturer ",
manufacturer,
"')~\n'This is the model ",
model,
"'"
)
)
mpg_df %>%
ggplot(aes(x = cty, y = hwy)) +
geom_point() +
facet_wrap( ~ title, labeller = label_parsed) +
theme_classic()
But they end up on the same line, and I'm not sure how to work atop
into this, since \n
does not work with plotmath.
I tried many other things for mutate
with no luck, such as:
mutate(title = bquote(
"atop(bold(This~is~the~manufacturer.(manufacturer)),
This~is~the~model.(national))")
Using ggtext
you could do add in markdown or html syntax to fit your needs
library(ggplot2)
library(ggtext)
suppressPackageStartupMessages(library(dplyr))
mpg_df <- mpg %>%
select(year, manufacturer, model, cty, hwy) %>%
filter(
year == 1999 & manufacturer == "audi" & model == "a4 quattro" |
year == 2008 &
manufacturer == "dodge" & model == "ram 1500 pickup 4wd"
) %>%
mutate(
title = paste0(
"**This is the manufacturer ",
manufacturer,"**",
" <br>This is the model ",
model
)
)
mpg_df %>%
ggplot(aes(x = cty, y = hwy)) +
geom_point() +
facet_wrap(vars(title)) +
theme_classic() +
theme(strip.text = element_markdown())
Created on 2024-08-16 with reprex v2.1.1