How do I plot a function with a summation in ggplo

2019-08-09 04:49发布

问题:

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.

回答1:

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 with

f <- Vectorize(function(k, vector){
    sum((vector-k)^2/5)
}, "k")

Secondly, args= is a parameter, not a function when callingg stat_function. Use

ggplot(data=data.frame(x=c(0, 5)), aes(x)) +
    stat_function(fun=f, geom='line', args=list(vector=y))

This will give you