ggplot2:在自变量上绘制积分的简单方法? [英] ggplot2: easy way to plot integral over independent variable?
问题描述
我正在集成函数 f(t)= 2t
(仅作为示例),并希望使用作为时间 t
的函数来绘制积分.>
I'm integrating a function f(t) = 2t
(just an example) and would like to plot the integral as a function of time t
using
awesome_thing <- function(t) {2*t}
integrate(awesome_thing, lower=0, upper=10)
但是,我想在ggplot2中将积分绘制为时间的函数,因此在此示例中,绘制的点将是(1,1),(2,4),(3,9),...,(10,100).
However, I would like to plot the integral as a function of time in ggplot2, so for this example the plotted points would be (1,1), (2,4), (3,9), ..., (10,100).
在ggplot中是否有一种简单的方法(例如,类似于如何绘制函数的图)?我知道我可以手动"评估和绘制每个 t
的数据,但是我想我可以看看是否有人可以推荐一种更简单的方法.
Is there an easy way to do this in ggplot (e.g., something similar to how functions are plotted)? I understand I can "manually" evaluate and plot the data for each t
, but I thought i'd see if anyone could recommend a simpler way.
推荐答案
这是 ggplot
解决方案和 stat_function
# create a function that is vectorized over the "upper" limit of your
# integral
int_f <- Vectorize(function(f = awesome_thing, lower=0,upper,...){
integrate(f,lower,upper,...)[['value']] },'upper')
ggplot(data.frame(x = c(0,10)),aes(x=x)) +
stat_function(fun = int_f, args = list(f = awesome_thing, lower=0))
这篇关于ggplot2:在自变量上绘制积分的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!