Marc in the box
Marc in the box

Reputation: 11995

Error using bquote() for axis labelling

I'm experiencing a strange error when using the function bquote for axis labeling. The error is only occurring when applying the label (the greek symbol "mu") to the y-axis:

df <- data.frame(x=1:10, y=1:10)
plot(y~x, df, t="l", xlab=bquote(.("Size [")*mu*m*.("]"))) # works
plot(y~x, df, t="l", ylab=bquote(.("Size [")*mu*m*.("]"))) # doesn't work
# Error in plot.default(1:10, 1:10, ylab = "Size [" * mu * m * "]", xlab = quote("x"),  : object 'mu' not found

I know I could use expression as an alternative in this case, but I'm trying to understand the error.

Upvotes: 1

Views: 279

Answers (1)

A. Webb
A. Webb

Reputation: 26436

This is due to subtleties of evaluation rules and the specifics of the implementation of this plotting function.

Note that this does not occur when not using the formula interface

plot(df$x,df$y, type="l", ylab=bquote(.("Size [")*mu*m*.("]"))) #works as you expect

To see what is happening, examine the source

getAnywhere("plot.formula")

and you'll see the equivalent of this simplified example

plotex<-function(x,y,type="l",ylab,...) {
  m=match.call(expand.dots = FALSE)
  dots <- lapply(m$..., eval)
  dots$xlab <- enquote(dots$xlab)
  do.call(plot,c(list(x=x,y=y,type=type,ylab=ylab),dots))
}

The xlab argument is in ... and protected against evaluation with an explicit enquote. The ylab is a named parameter and its evaluation is forced by inclusion in the list provided to do.call.

Upvotes: 2

Related Questions