Reputation: 306
The following works well (I get the right plots):
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()
however, if I merge the two functions myplot1 and myplot2 as in
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)
}
and so use
p <- ggplot()
p <- p + myplot(df,"X1","black")
p <- p + myplot(df,"X2","blue")
p + theme_minimal()
I get
Error [...] non-numeric argument to binary operator
How can I solve this issue ?
Upvotes: 2
Views: 2754
Reputation: 386
For some reason combining those geoms is causing a problem. You can return them as a list and get it to work:
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()
Upvotes: 2