2

I want to add a formula with variables in it as a annotation onto my ggplot.

regline1 <- 0.00
slope1 <- 1.00
dat <- as.data.frame(c(0,1))
dat[2] <- c(0,1)
names(dat) <- c("foo","bar")

p <-
ggplot(dat, aes(foo, bar)) + coord_fixed(ratio = 1) + geom_point()  + 
geom_abline(slope = slope1, intercept = intercept1, linetype = "dashed") +
labs(x =  substitute(y[H1]==i+s%*%x,list(i=format(intercept1, digits = 1), s= format(slope1, digits = 1))))

As you can see it is no problem for ggplot to evaluate the formula for labs(x =...), but if you try to add an annotation:

p +   annotate("text",x=0.75, y = 0.25, label = substitute(y[H1]==i+s%*%x,list(i=format(intercept1, digits = 1), s= format(slope1, digits = 1))))

it will give you an Error:

Error: Aesthetics must be either length 1 or the same as the data (1): label

I can parse a paste-call in annotate() like this:

p <- annotate("text",x= 0.75, y =0.25, label = "paste(y[H1]== intercept1+ slope1 %.%x)", parse = TRUE)

However, this does not write the variable values, since its in quotation marks. The substitute()-expression in quotation marks will not be parsed at all.

So how can I do this?

Any help is appreciated, thanks in advance Julius

Julius Diel
  • 157
  • 1
  • 8
  • annotate("text",x= 0.75, y =0.25, label = "bquote(y[H2]==.(intercept2)+.(slope2)%.%x)", parse = TRUE) does not get parsed as well – Julius Diel Apr 06 '17 at 18:16

1 Answers1

4

The annotate() function does not support expressions. you need to pass in a string and set parse=T.

If you first build your expression

myexpr <- substitute( y[H1]==i+s%*%x, list(
    i = format(intercept1, digits = 1), 
    s= format(slope1, digits = 1))
)

You can deparse() it and have annotate() re-parse it for you

ggplot(dat, aes(foo, bar)) + 
    geom_point()  + 
    geom_abline(slope = slope1, intercept = intercept1, linetype = "dashed") +
    coord_fixed(ratio = 1) + 
    labs(x = myexpr) + 
    annotate("text",x=0.75, y = 0.25, label = deparse(myexpr), parse=TRUE)

which results in

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • I don't. I just tried with your example above in a fresh R session (after setting `intercept1<-0`). Tested with `R 3.3.1` and `ggplot2_2.2.1` – MrFlick Apr 06 '17 at 19:04
  • Yes, you are right. In an empty session it works for me as well, but with my real data the error consists... 'myexpr' works fine in lab(x=...) but not as annotate. I don't get it – Julius Diel Apr 06 '17 at 19:17
  • Without a reproducible example, it's really hard to guess what might be going on. – MrFlick Apr 06 '17 at 19:18
  • It is a problem of how i get slope1 and intercept1 from my regession1. with: slope1 <- regline1$coefficients[2]; intercept1 <- regline1$coefficients[1] I get named numbers, which can not be parsed (?). So I have to unname them with as.numeric. This did the trick. Thanks for the fast answer! – Julius Diel Apr 06 '17 at 19:27