Adding a newline in a substitute() expression

家住魔仙堡 提交于 2019-12-07 13:51:49

问题


I'm trying to annotate a plot in ggplot with relevant data from a regression model. I've followed the suggestions in this SO post and tried to modify the function to have a couple additional items in a newline in the plot. This is my attempt at a new function:

lm_eqn = function(m){
  eq <- substitute(italic(y) == a %.% italic(x)^b*","~~italic(r)^2~"="~r2*","~~italic(n)~"="~nn*","~~italic(p-value)~"="~pv, 
                   list(a = format(exp(coef(m)[1]), digits = 3), 
                        b = format(coef(m)[2], digits = 3), 
                        r2 = format(summary(m)$r.squared, digits = 3),
                        nn=format(summary(m)$df[2]),
                        pv=format(summary(m)$coefficients[,4][2])))
  as.character(as.expression(eq));                 
}

It produces the expected output: all in one line. But I'd like to split the text in two lines, the second one starting with italic(n)=. But if I introduce a \n, it throws an error when it finds \n. If I introduce the \n inside the quotes: "\n" then it seems to be ignored and the text remains in one line. I haven't found any reference as to how to introduce a newline in such an expression. Your kind help will be much appreciated.

Thanks.

EDIT: following a coment by @Tim I present a rewriten code and adjusted question.


回答1:


\n cannot be used in plotmath expressions. You could perhaps break the expression in two parts, and use annotate to add the expressions where you want them. Or, use atop. Check out this post -> Line break in expression()?



来源:https://stackoverflow.com/questions/29112697/adding-a-newline-in-a-substitute-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!