在R(ggplot)中注释公式(使用bqoute或替代项)会产生错误 [英] annotate a formula (with bqoute or substitute) in R (ggplot) gives Error

查看:82
本文介绍了在R(ggplot)中注释公式(使用bqoute或替代项)会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在其中添加一个带有变量的公式作为对ggplot的注释.

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))))

如您所见,ggplot为labs(x = ...)计算公式是没有问题的,但是,如果您尝试添加批注:

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))))

它会给您一个错误:

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

我可以这样解析annotate()中的粘贴调用:

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)

但是,由于它用引号引起来,因此不会写入变量值.不会完全解析引号中的replace()表达式.

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.

那我该怎么办呢?

感谢您的帮助, 提前致谢 朱利叶斯

Any help is appreciated, thanks in advance Julius

推荐答案

annotate()函数不支持表达式.您需要传递一个字符串并设置parse=T.

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

如果您首先构建表达式

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

您可以deparse()它,并让annotate()为您重新解析

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)

这将导致

这篇关于在R(ggplot)中注释公式(使用bqoute或替代项)会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆