Reputation: 1417
So my example data are:
x <- runif(1000, min = 0, max = 5)
y <- (2 / pi) * atan(x)
z <- floor(x)
df <- data.frame(x, y, z)
I draw boxplots of x, binned by z:
library(ggplot2)
g <- ggplot(df, aes(x = x, y = y, group = z)) +
geom_boxplot()
g
But the thing is, in my real-life data, I'm not completely sure that the y-values follow (2 / pi) * atan(x)
. There's a random element there. So, how do I draw the function on top of my graph to see for myself? As per the ggplot2 documentation, I tried...
g + stat_function(fun = (2 / pi) * atan(x), colour = "red")
...but am receiving the error Warning message:
Computation failed in 'stat_function()':
'what' must be a function or character string
.
Upvotes: 2
Views: 3606
Reputation: 11659
The error is saying:
'what' must be a function or character string
so it is asking you simply define your function.
You need to define your function suuch as func
func<-function(x){ (2 / pi) * atan(x)}
and then call it in ggplot
library(ggplot2)
g <- ggplot(df, aes(x = x, y = y, group = z)) +
geom_boxplot()
g+stat_function(fun = func, colour = "red")
Here is the result
Upvotes: 4
Reputation: 171
I could solve your problem by simply defining a new function and the pass it to as the argument of stat_function
Here it is
myfun <- function(x){(2 / pi) * atan(x)}
and then
g + stat_function(fun = myfun colour = "red")
would do it
Upvotes: 3
Reputation: 35737
the parameter fun
must be a function
g + stat_function(fun = function(x){(2 / pi) * atan(x)}, colour = "red")
Upvotes: 3