Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving errors when trying to use stat_function in ggplot

Tags:

r

ggplot2

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

enter image description here

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.

like image 985
mmyoung77 Avatar asked Sep 07 '26 23:09

mmyoung77


1 Answers

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

enter image description here

like image 98
Sal-laS Avatar answered Sep 10 '26 13:09

Sal-laS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!