【问题标题】:ggplot2 in function: non-numeric argument to binary operator函数中的ggplot2:二元运算符的非数字参数
【发布时间】:2017-11-11 20:55:34
【问题描述】:

以下效果很好(我得到了正确的情节):

library(ggplot2)

myfunc <- function(x)
{
  n = length(x)
  return(sqrt(x)+rnorm(n,0,0.05))
}

myplot1 <- function(df,x,color)
{
  df$y <- myfunc(df[[x]])
  p  <- geom_point(data=df,
                   aes_string(x=x,y="y"),
                   colour=color) 
  return(p)
}

myplot2 <- function(df,x,color)
{
  df$y <- myfunc(df[[x]])
  p  <- geom_smooth(data=df,
                   aes_string(x=x,y="y"),
                   colour=color,
                   method="lm") 
  return(p)
}

n <- 100
df <- data.frame( X1 = runif(n,0,1),
                  X2 = rnorm(n,0.5,0.01))
p <- ggplot()
p <- p + myplot1(df,"X1","black") + myplot2(df,"X1","black")
p <- p + myplot1(df,"X2","blue")  + myplot2(df,"X2","blue")
p + theme_minimal()

但是,如果我将两个函数 myplot1 和 myplot2 合并为

myplot <- function(df,x,color)
{
  df$y <- myfunc(df[[x]])
  p  <- geom_point(data=df,
                   aes_string(x=x,y="y"),
                   colour=color)  +
        geom_smooth(data=df,
                      aes_string(x=x,y="y"),
                      colour=color,
                      method="lm")
  return(p)
}

所以使用

p <- ggplot()
p <- p + myplot(df,"X1","black")
p <- p + myplot(df,"X2","blue")
p + theme_minimal()

我明白了

错误 [...] 二元运算符的非数字参数

我该如何解决这个问题?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    由于某种原因,组合这些几何图形会导致问题。您可以将它们作为列表返回并使其工作:

    library(ggplot2)
    
    n <- 100
    df <- data.frame( X1 = runif(n,0,1),
                      X2 = rnorm(n,0.5,0.01))
    
    myfunc <- function(x)
    {
      n = length(x)
      return(sqrt(x)+rnorm(n,0,0.05))
    }
    
    myplot <- function(mydata,x,color)
    {
      mydata$y <- myfunc(mydata[[x]])
      p <- geom_point(data = mydata, aes_string(x = x, y = 'y'), color = color)
      q <- geom_smooth(data = mydata, aes_string(x = x, y = 'y'), color = color, method = 'lm')
      return(list(p, q))
    }
    
    
    p <- ggplot()
    p <- p + myplot(df,"X1","black")
    p <- p + myplot(df,"X2","blue")
    p + theme_minimal()
    

    【讨论】:

    • 谢谢!它有效,我不会想出这样的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2019-11-20
    相关资源
    最近更新 更多