jimjamslam
jimjamslam

Reputation: 2067

Adjust geom position along discrete scale

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?

Upvotes: 3

Views: 3093

Answers (1)

ddiez
ddiez

Reputation: 1127

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)

Upvotes: 5

Related Questions