3

I'm trying to position text annotations on a plot that has both facets and a discrete axis. I can tie the position of the annotations to the points using aes(), but I'd like to budge them a little to keep the points readable. This is fine if the nudge is on a numeric scale:

data <- data.frame(
    category = c("blue", "yellow", "red", "green"),
    rating = 1:4)

gp <- ggplot(data) + geom_point(aes(x = category, y = rating)) +
    geom_text(aes(label = "I have a label!", x = category, y = rating + 0.5))

But if I try to do it on a non-numeric scale (in this case, character) it fails:

gp <- ggplot(data) + geom_point(aes(x = category, y = rating)) +
    geom_text(aes(label = "I have a label!", x = category + 0.5, y = rating))
gp

Error in unit(x, default.units) : 'x' and 'units' must have length > 0
In addition: Warning messages:
1: In Ops.factor(category, 0.5) : + not meaningful for factors
2: Removed 4 rows containing missing values (geom_text).

I could use hjust and vjust to move them a little, but since these are designed to align text rather than position it, they don't really move the annotations far enough away even at their greatest extent. Is there a way to determine the numeric scale maps the discrete variable to, or another way to manually adjust the geom_text's position?

jimjamslam
  • 1,988
  • 1
  • 18
  • 32
  • hjust can be used for position. This works for me (is this what you are looking for?): ggplot(data) + geom_point(aes(x = category, y = rating)) + geom_text(aes(label = "I have a label!", x = category, y = rating), hjust=-.1) – ddiez Sep 23 '14 at 03:51
  • @ddiez Why don't you post this as an answer? – jlhoward Sep 23 '14 at 03:55
  • Mmm, I'm sorry - I tested `hjust` and `vjust` in the plot I'm working on but not in the MRE above. I was under the impression that `hjust` and `vjust` could only be used within a domain of [-1, 1], and although small values looked fine in the MRE above, they weren't moving enough in my own plots. Just tested `vjust = 4` in my own plot and it does move further. However, it does break alignment of multi-line labels. – jimjamslam Sep 23 '14 at 04:07
  • I was referring to [this question](http://stackoverflow.com/questions/7263849/what-do-hjust-and-vjust-do-when-making-a-plot-using-ggplot) for the `hjust` and `vjust` definitions. – jimjamslam Sep 23 '14 at 04:09
  • @rensa I see. That post is from 2011- things might have changed. However I do not know at this moment of a more definite solution. An alternative can be to use annotate("text") – ddiez Sep 23 '14 at 04:47
  • Thanks very much, @ddiez. If I use annotate("text"), do you know how I can map the position to the non-numeric scale? – jimjamslam Sep 23 '14 at 04:50

1 Answers1

4

You can use hjust (or vjust) to position text:

ggplot(data) + geom_point(aes(x = category, y = rating)) + 
    geom_text(aes(label = "I have a label!", x = category, y = rating), hjust=-.1)
ddiez
  • 1,087
  • 11
  • 26