如何在ggplot2中绘制总和函数? [英] How do I plot a function with a summation in ggplot2?

查看:95
本文介绍了如何在ggplot2中绘制总和函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个向量 x = 1:5 。假设我想绘制公式





其中。 请注意, k 具有[0,5]中的所有值,而不仅仅是整数。



我会如何去做 ggplot2



这是我的尝试:

  library(ggplot2)
y < - c(1,2,3,4,5)
f< - 函数(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)))

(function(k,vector) :
参数vector丢失,没有默认
存在错误(name,envir = env,mode = mode):
参数env丢失,没有默认值

我道歉,如果我看起来很无知;我是 ggplot2

解决方案

首先,您的函数需要对想要绘制的变量进行适当的矢量化。 c $ c> sum 会折叠结果。最简单的方法是使用 (函数(k,向量){
sum((向量-k)^ 2/5)向量化)
},k)

其次, args = 是一个参数,而不是调用 stat_function 时的函数。使用

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

这会给你


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 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

这篇关于如何在ggplot2中绘制总和函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆