3

My data :

dat <- data_frame(x = c(1,2,3,4,5,6), y = c(2,2,2,6,2,2))

I wish to display this expression beside the point (x=4,y=6) :

expression <- bquote(paste(frac(a[z], b[z]), " = ", .(dat[which.max(dat$y),"y"] %>% as.numeric())))

But, when I am using this expression with ggplot :

ggplot() + 
  geom_point(data = dat, aes(x = x, y = y)) + 
  geom_label(data = dat[which.max(dat$y),], aes(x = x, y = y, label = expression))

I get this error message :

Error: Aesthetics must be either length 1 or the same as the data (1): label
Loulou
  • 703
  • 5
  • 17

1 Answers1

5

You could use the following code (keeping your definitions of the data and the expression):

Not related to your question, but: it is always better to define aesthetics in the ggplot-call and get it reused in the subsequent function calls. If needed, you may override the definitions, like done below in geom_label

ggplot(data = dat, aes(x = x, y = y)) + 
  geom_point() + 
  geom_label(data = dat[4,], label = deparse(expression), parse = TRUE, 
             hjust = 0, nudge_x = .1)

hjust and nudge_x are used to position the label relative to the point. One could argue to use nudge_y as well to get the whole label in the picture.

yielding this plot:

enter image description here

Please let me know whether this is what you want.

KoenV
  • 4,113
  • 2
  • 23
  • 38
  • 1
    My pleasure. Glad I could help. – KoenV Dec 20 '18 at 10:35
  • I would not say it is almost always better to define the `aes` in the main `ggplot` call. But in the end, I guess it's also about style. If you know that you will use the same aes for all plots - well, of course, define it in the main call – tjebo Dec 20 '18 at 11:19