Jul*_*iel 2 r annotate formula ggplot2
我想添加一个包含变量的公式作为我的 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))))
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,ggplot 计算 labs(x =...) 的公式是没有问题的,但是如果您尝试添加注释:
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))))
Run Code Online (Sandbox Code Playgroud)
它会给你一个错误:
Error: Aesthetics must be either length 1 or the same as the data (1): label
Run Code Online (Sandbox Code Playgroud)
我可以像这样解析 annotate() 中的粘贴调用:
p <- annotate("text",x= 0.75, y =0.25, label = "paste(y[H1]== intercept1+ slope1 %.%x)", parse = TRUE)
Run Code Online (Sandbox Code Playgroud)
但是,这不会写入变量值,因为它用引号引起来。引号中的 Replace() 表达式根本不会被解析。
那么我该怎么做呢?
感谢任何帮助,提前感谢朱利叶斯
annotate () 函数不支持表达式。您需要传入一个字符串并设置parse=T。
如果你首先构建你的表达式
myexpr <- substitute( y[H1]==i+s%*%x, list(
i = format(intercept1, digits = 1),
s= format(slope1, digits = 1))
)
Run Code Online (Sandbox Code Playgroud)
你可以deparse()它并annotate()为你重新解析它
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)
Run Code Online (Sandbox Code Playgroud)
这导致