rplotaxisaxis-labelssuperscript

Getting Superscripts in Plot Axis Labels Using Character String Columns From a Data Frame


I have a data frame of variable names and units.

df1 <- data.frame(Variable = paste('Variable', 1:4), Unit = c('mm', 'cm ^ 2', 'cm ^ 2 * hr ^ -1', 'cm ^ 3 * cm ^ -2 * hr ^ -1'))
# > df1
#     Variable                       Unit
# 1 Variable 1                         mm
# 2 Variable 2                     cm ^ 2
# 3 Variable 3           cm ^ 2 * hr ^ -1
# 4 Variable 4 cm ^ 3 * cm ^ -2 * hr ^ -1

I want to use these when I generate plots' axis labels. Here's some example code I was playing around with.

par(mfrow = c(2, 2))
for (u in 1:4) {
  plot(0, xlab = paste0(df1[u, ]$Variable, ', ', bquote(.(df1[u, ]$Unit))))
}

Here's what those plots look like. You can see how the superscripts aren't working properly.

enter image description here

How can I get the superscripts I want? I've used the expression(), paste(), and bquote() functions before, but never for this specific combination of objects (such as the data frame I'm using that contains a column of the units), superscripts, and arithmetic operators. I'm not sure if I need to reformat the unit column somehow or change how I'm generating the axis labels in the plot() function.

Thanks!


Solution

  • Using str2lang. I'd put it in an mtext.

    par(mfrow = c(2, 2))
    for (u in 1:4) {
      plot(0, ann=FALSE)
      mtext(bquote(.(df1[u, ]$Variable)*', '~.(str2lang(df1[u, ]$Unit))), 1, 3)
    }
    

    enter image description here


    Data:

    df1 <- structure(list(Variable = c("Variable 1", "Variable 2", "Variable 3", 
    "Variable 4"), Unit = c("mm", "cm ^ 2", "cm ^ 2 * hr ^ -1", "cm ^ 3 * cm ^ -2 * hr ^ -1"
    )), class = "data.frame", row.names = c(NA, -4L))