在 R (ggplot) 中注释公式(使用 bqoute 或替代)给出错误
annotate a formula (with bqoute or substitute) in R (ggplot) gives Error
我想在我的 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))))
正如你所看到的,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))))
它会给你一个错误:
Error: Aesthetics must be either length 1 or the same as the data (1): label
我可以像这样解析 annotate() 中的粘贴调用:
p <- annotate("text",x= 0.75, y =0.25, label = "paste(y[H1]== intercept1+ slope1 %.%x)", parse = TRUE)
但是,这不会写入变量值,因为它在引号中。引号中的substitute()-表达式根本不会被解析
那我该怎么做呢?
感谢任何帮助,
提前致谢
朱利叶斯
annotate() function does not support expressions。您需要传入一个字符串并设置 parse=T
.
如果您首先构建表达式
myexpr <- substitute( y[H1]==i+s%*%x, list(
i = format(intercept1, digits = 1),
s= format(slope1, digits = 1))
)
您可以 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)
结果是
我想在我的 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))))
正如你所看到的,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))))
它会给你一个错误:
Error: Aesthetics must be either length 1 or the same as the data (1): label
我可以像这样解析 annotate() 中的粘贴调用:
p <- annotate("text",x= 0.75, y =0.25, label = "paste(y[H1]== intercept1+ slope1 %.%x)", parse = TRUE)
但是,这不会写入变量值,因为它在引号中。引号中的substitute()-表达式根本不会被解析
那我该怎么做呢?
感谢任何帮助, 提前致谢 朱利叶斯
annotate() function does not support expressions。您需要传入一个字符串并设置 parse=T
.
如果您首先构建表达式
myexpr <- substitute( y[H1]==i+s%*%x, list(
i = format(intercept1, digits = 1),
s= format(slope1, digits = 1))
)
您可以 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)
结果是