Search code examples
rlabelplotmath

How to automate graph axis labeling with plotmath expressions?


I am trying to create multiple graphs with ggplot2 through using multiple instances of its plotting function and assign proper y-axis labels (with plotmath) to each function. Below is some code that demonstrates my failed solution. (mind the silliness)

library(tidyverse)

df <- tibble(
  measure = c('Current', 'Resistance', 'Volts'),
  mean = c(532, 42, 50),
  sd = c(45, 6, 8),
  ylabel = c('Amps (A)', 'Ohms (Omega)', 'Volts (V)')
)

for (i in 1:3)) {
  g <- ggplot(df[i,], aes(x = measure, y = mean)) + 
    geom_point(size = 7) +
    geom_errorbar(aes(ymax = mean + sd, ymin = mean - sd), width = .25) +
    ylab(expression(df[i,]$ylabel))

  ggsave(g, paste0('~/Desktop/', df$measure[i]))

}

I am running into a problem with expression() and its placing of special characters. How would you get around this problem?


Solution

  • Try parse instead of expression:

    ylab(parse(text = df[i, ]$ylabel))