0

Here is a sample dataframe:

df <- tibble(variable =c("gdp", "gdp_ppp"),
             value = c(1000, 2000),
             variable_label=c("GDP", "GDP_PPP"))

I would like to make variable_label an expression or text element of some sort because I want to use it as a title for a series of plots that I have generated using a loop. I could manually type the title using text elements but that would require me to generate each plot independently, as far as I know. For example, I want the "PPP" in "GDP_PPP" to be a subscript when it shows up in the title. Is this possible? Thanks!

dd_data
  • 93
  • 5
  • Where is your code to make the plots? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 23 '22 at 20:30

2 Answers2

0

If your intention was to specify latex math and have it translated to plotmath then use the latex2exp package on cran. Use the code below or in ggplot2 + ggtitle(TeX("$GDP_{PPP}$")) .

library(latex2exp)
plot(1, main = TeX("$GDP_{PPP}$"))

(continued after chart) screenshot

The input shown in the question is not proper latex, latex or plotmath but looks closer to latex and we could translate it to proper latex if it is necessary to use the form shown in the question. The code below gives the same output as shown above or we could alternately use + ggtitle(TeX(ltx)) if we were using ggplot2.

ltx <- sprintf("$%s$", gsub("_(\\w+)", "_{\\1}", "GDP_PPP")) #  $GDP_{PPP}$

plot(1, main = TeX(ltx))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

You can use parse to convert the strings to expressions. Here's an example of doing that in a loop using ggplot, with which your question was tagged

library(tidyverse)

df <- tibble(variable =c("gdp", "gdp_ppp"),
             value = c(1000, 2000),
             variable_label = c("GDP", "GDP[PPP]"))

for(i in seq(nrow(df))) {
  print(ggplot(df[i,], aes(variable, value)) + 
    geom_col() +
    ggtitle(parse(text = df$variable_label[i])))
}

Created on 2022-11-23 with reprex v2.0.2

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87