Search code examples
rr-gridplotmath

Alternative to Vector of Plotmath Expressions


I'm trying to label an axis at every 3rd tick with a 10^n value, formatted as a superscript. I'm using grid graphics. I'm doing something bassackwards. Here's a MWE (or I see there is some movement to call it a reprex):

library("grid")
grid.newpage()
axisVP <- viewport(width = unit(6, "inches"), height = unit(0.01, "inches"))
pushViewport(axisVP)
labs <- c(1, "", "", expression(10^{-3}), "", "", expression(10^{-6}), "", "",
   expression(10^{-9}), "", "", expression(10^{-12}))
grid.xaxis(at = seq(0, 1, length.out = 15)[-c(1,15)], label = labs)

However, this only labels the first tick with 1. Looking at str(labs) it is an expression with length 13 as expected. And expressions are accepted by grid.xaxis. So I'm not quite sure why only the first value is being displayed. I've explored related questions on SO but most seem to deal with a single expression as an axis label or title, not a series of expressions. And most questions dealing with axis labels seek to label every tick using a specialized function.


Solution

  • Here's what I'd do:

    library(grid)
    grid.newpage()
    axisVP <- viewport(width = unit(6, "inches"), height = unit(0.01, "inches"))
    pushViewport(axisVP)
    
    ## First plot an axis with all ticks and no labels
    ticks_at <- seq(1/15, 14/15, length.out=13)
    grid.xaxis(at = ticks_at, label=FALSE)
    
    ## Then add labels where you want them
    labs <- parse(text=c("1", "10^{-3}", "10^{-6}", "10^{-9}", "10^{-12}"))
    ## Alternatively, use this, though in practice it's more cumbersome
    # labs <- c(expression(1), expression(10^{-3}), expression(10^{-6}), 
    #           expression(10^{-9}), expression(10^{-12}))
    labs_at <- seq(1/15, 14/15, length.out=5)
    grid.xaxis(at = labs_at, label = labs)
    

    enter image description here