I am looking to add subscripts to a chart title in ggplot, to look something like:
The values of k1, k2 and k3 are stored in variables: k1
, k2
and k3
data <- data.frame(age = 30:32, count = 2:4)
k1 <- 2
k2 <- 9
k3 <- 4
I have been able to add in the variable names and values by pasting together an expression and parsing it, as explained here:
title <- paste0("k[1]*", k1, "~k[2]*", k2, "~k[3]*", k3)
title_parsed <- parse(text = title)
data %>%
ggplot(aes(x = age, y = count)) +
geom_point() +
ggtitle(title_parsed)
which gives:
And have been able to get the fixed parts of the title (equals signs and comma) to display correctly using bquote (but cannot add in the values of k from my variables):
data %>%
ggplot(aes(x = age, y = count)) +
geom_point() +
ggtitle(bquote(k[1]*" = ," ~k[2]*" = and" ~ k[3]*" = "))
I have also been able to combine these to produce a short title, with a single k value:
title <- paste0("k[1]*", "\" = \"*", k1)
title_parsed <- parse(text = title)
data %>%
ggplot(aes(x = age, y = count)) +
geom_point() +
ggtitle(title_parsed)
But for longer titles with multiple k values, I have been unable to parse a text string with a number next to a comma. (e.g. both of the below values of title
throw an error when fed into the parse function)
title <- paste0("k[1]*", "\" = \"*", k1, "*,")
title <- paste0("k[1]*", "\" = \"*", k1, ",")
title_parsed <- parse(text = title)
The issue seems unique to commas and other special characters, as I can add other text after the number:
title <- paste0("k[1]*", "\" = \"*", k1, "~text")
title_parsed <- parse(text = title)
What am I doing wrong? I wondered if I needed to use escape characters before the comma, but no combination of \, \\ and \\\ seems to work.
You can use the .()
operator inside bquote
to refer to an external variable. Additionally, you could use the ==
operator to generate an equals sign.
data %>%
ggplot(aes(x = age, y = count)) +
geom_point() +
theme_gray(20) +
ggtitle(bquote(k[1] == .(k1) * "," ~ k[2] == .(k2) * " and" ~ k[3] == .(k3)))