在R中的用户定义函数中使用图例

时间:2015-04-30 03:24:46

标签: r

首先,我对R的知识处于婴儿阶段,所以如果我遇到无知,请原谅我。

我正在编写一个用户定义的函数,它将R ^ 2和p值放在带有线性回归的散点图上。这是迄今为止的代码:

stats.insert <- function(data, x, y)
{
reg1<-with(data,lm(y~x))
fit<-abline(reg1, col="blue")
modsum = summary(reg1)
r2=modsum["r.squared"]
my.p <- coef(modsum)[2,4]
rp=vector('expression',2)
rp[1]=substitute(expression(italic(R)^2==MYVALUE),
   list(MYVALUE=format(r2,dig=3)))[2]
rp[2]=substitute(expression(italic(p)== MYOTHERVALUE),
  list(MYOTHERVALUE=format(my.p,digits=2)))[2]       
legend("bottomleft",legend=rp,bty='n')
}

这很好,但是,我还要指定图例的位置。所以函数看起来像这样:

stats.insert <- function(data, x, y, placement)

其中展示位置位于图例功能中。我遇到的问题是我无法绕过&#34;&#34;在图例功能中。

任何建议都将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

错误:

stats.insert <- function(data, x, y,placement="bottomleft")
{

    lots of code ...

    legend(placement,legend=rp,bty='n')
}

答案 1 :(得分:0)

欢迎来到R和SO。

有很多方法可以创建一个适合您的目的的功能。

# Function stats.insert
# Args: 
#   formula : see ?lm
#   data:  a data.frame, see ?lm
#   ...    Arguments passed to the legend() for the plot
#
# Return:
#   A plot of the data with the regression line, and the coefficient of
#   determination, and a p-value in a legend.

stats.insert <- function(formula, .data, ...) {
  reg1 <- lm(formula, data = .data)

  modsum <- summary(reg1)
  r2     <- format(modsum["r.squared"], digits = 3)
  my.p   <- format(coef(modsum)[2,4], digits = 2)

  rp     <- vector('expression', 2)
  rp[1]  <- substitute(expression(italic(R)^2==MYVALUE),list(MYVALUE=format(r2,dig=3)))[2]
  rp[2]  <- substitute(expression(italic(p)== MYOTHERVALUE), list(MYOTHERVALUE=format(my.p,digits=2)))[2]       

  abline(reg1, col="blue")
  legend(..., legend = rp, bty = 'n')
}

with(mtcars, plot(wt, mpg))
stats.insert(mpg ~ wt, mtcars, "bottomright")
stats.insert(mpg ~ wt, mtcars, "topright")
stats.insert(mpg ~ wt, mtcars, x = 2, y = 15)

enter image description here