Let's say I have a vector x = 1:5
. Suppose I wanted to plot the formula
where in this example. Note that k
takes on all values in [0, 5], rather than just integers.
How would I go about doing this in ggplot2
?
Here is my attempt:
library(ggplot2)
y <- c(1, 2, 3, 4, 5)
f <- function(k, vector){
sum((vector-k)^2/5)
}
ggplot(data=data.frame(x=c(0, 5)), aes(x)) +
stat_function(fun=f, geom='line', args(list(vector=y)))
Error in (function (k, vector) :
argument "vector" is missing, with no default
Error in exists(name, envir = env, mode = mode) :
argument "env" is missing, with no default
I apologize if I seem ignorant; I am new to ggplot2
.
Two things. First, your function needs to be properly vectorized for the variable you want to plot.
sum
will collapse the result. The easiest way to fix is withSecondly,
args=
is a parameter, not a function when callinggstat_function
. UseThis will give you