gpt4 book ai didi

r - 在 R (ggplot) 中注释公式(使用 bqoute 或替代)给出错误

转载 作者:行者123 更新时间:2023-12-03 09:10:01 24 4
gpt4 key购买 nike

我想将一个包含变量的公式作为注释添加到我的 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)

但是,这不会写入变量值,因为它用引号引起来。引号中的 Replace() 表达式根本不会被解析。

那么我该怎么做呢?

感谢任何帮助,提前致谢朱利叶斯

最佳答案

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)

结果

enter image description here

关于r - 在 R (ggplot) 中注释公式(使用 bqoute 或替代)给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com