简体   繁体   English

如何在ggplot2中使用求和绘制函数?

[英]How do I plot a function with a summation in ggplot2?

Let's say I have a vector x = 1:5 . 假设我有一个向量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. 请注意, k接受[0,5]中的所有值,而不仅仅是整数。

How would I go about doing this in ggplot2 ? 我将如何在ggplot2执行此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 . 我是ggplot2

Two things. 两件事情。 First, your function needs to be properly vectorized for the variable you want to plot. 首先,您的函数需要针对要绘制的变量进行适当的矢量化。 sum will collapse the result. sum会使结果崩溃。 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 . 其次, args=是一个参数,而不是调用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 这会给你

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM