问题
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
回答1:
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
来源:https://stackoverflow.com/questions/43262808/annotate-a-formula-with-bqoute-or-substitute-in-r-ggplot-gives-error