21

I'm trying to add panel labels to different facets in a plot. I want them to be 1:7, but, the following code

d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
     xlim(0, 2) + stat_binhex(na.rm = TRUE) + opts(aspect.ratio = 1)

d1<-d + facet_wrap(~ color)

d1+annotate("text", x=0.25, y=1.5e+04, label=1:7)

yields

Error: When _setting_ aesthetics, they may only take one value. Problems: label

Now, I can supply a single value and get that replicated across all facets. But how can I have different labels in different facets using annotate()?

1 Answer 1

28

With annotate, you can't. But by setting up a data.frame and using it as the data source for a geom_text, it is easy (with a few bookkeeping aspects).

d1 + geom_text(data=data.frame(x=0.25, y=1.5e+04, label=1:7, 
                               color=c("D","E","F","G","H","I","J")), 
               aes(x,y,label=label), inherit.aes=FALSE)

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to add text to multiple rows, make sure that your colnames() in the text data.frame match those of the data you are about to plot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.