Search code examples
rplotcoercion

Adding data labels to boxplot in R


Here's my code:

iFacVector <- as.factor(c(1,1,1,1,10,1,1,1,12,9,9,1,10,12,1,9,5))

iTargetVector <- c(2,1,0,1,6,9,15,1,8,0,1,2,1,1,9,12,1)

bp <- plot(iFacVector,iTargetVector)
text(bp,tapply(iTargetVector,iFacVector,median),labels=tapply(iTargetVector,iFacVector,median),cex=.8)

I am getting the following (classic R) error:

Error in xy.coords(x, y, recycle = TRUE) : 
  (list) object cannot be coerced to type 'double'

The vectors I am passing are numeric so I don't know what the problem is. I have tried unlist() and as.vector(). I have also tried using bp$stats[3,] as the labels.


Solution

  • The help for text gives the arguments as

    text(x, ...)

    so the first argument in your code, bp, is being treated as the x coordinate for where to place the text. You can just leave off the bp and get better behavior. You might also want to add pos=3 to get a nicer placement of the text.