R 我可以在用户定义函数中使用ggplot()在单个绘图中绘制多条函数曲线吗?

R 我可以在用户定义函数中使用ggplot()在单个绘图中绘制多条函数曲线吗?,r,for-loop,ggplot2,plot,user-defined-functions,R,For Loop,Ggplot2,Plot,User Defined Functions,我试图构建一个用户定义的函数,它基本上在一个绘图中返回多个函数曲线的ggplot。该绘图将是以下绘图的复杂版本: library(ggplot2) p <- ggplot() + xlim(0,4) + xlab("x") p <- p + geom_function(fun = function(x) 1*x) p <- p + geom_function(fun = function(x) 2*x) p <- p + geom_functi

我试图构建一个用户定义的函数,它基本上在一个绘图中返回多个函数曲线的ggplot。该绘图将是以下绘图的复杂版本:

library(ggplot2)
 p <- ggplot() + xlim(0,4) + xlab("x")
 p <- p + geom_function(fun = function(x) 1*x)
 p <- p + geom_function(fun = function(x) 2*x)
 p <- p + geom_function(fun = function(x) 3*x)
 p <- p + geom_function(fun = function(x) 4*x)
 p
库(ggplot2)
p1)向函数添加一个
i
参数,并在
args=
中指定它,如下所示:

library(ggplot2)
plot_func1 <- function(i) {
   p <- ggplot() + xlim(0,i) + xlab("x")
   for (i in 1:i) {
     p <- p + 
        geom_function(fun = function(x, i) i*x, args = list(i = i))
   }
   print(p)
 }
plot_func1(4)
library(ggplot2)
plot_func3 <- function(i) {
   p <- ggplot() + xlim(0,i) + xlab("x")
   for (i in 1:i) {
     p <- p + geom_function(fun = substitute(function(x) i*x, list(i = i)))
   }
   print(p)
 }
plot_func3(4)
3)或将i替换为如下函数:

library(ggplot2)
plot_func1 <- function(i) {
   p <- ggplot() + xlim(0,i) + xlab("x")
   for (i in 1:i) {
     p <- p + 
        geom_function(fun = function(x, i) i*x, args = list(i = i))
   }
   print(p)
 }
plot_func1(4)
library(ggplot2)
plot_func3 <- function(i) {
   p <- ggplot() + xlim(0,i) + xlab("x")
   for (i in 1:i) {
     p <- p + geom_function(fun = substitute(function(x) i*x, list(i = i)))
   }
   print(p)
 }
plot_func3(4)
库(ggplot2)

plot_func3在美学层列表中,通过调用其
+
(通过未记录的
+.gg()
方法)来考虑运行ggplots的函数形式:


plot_func真棒!!非常感谢您的解决方案!!它们都工作得很好。我以前从任何一本书或一篇文章中都没有得到过这样的解决方案。我对第一种选择的效果有疑问。如果通过
args
提供,是否会强制求值?当OP cross在RStudio社区发布时,我也在尝试做同样的事情,我不得不使用
local
来解决这个问题。否则,它总是采用计数器的最新更新值。它对我有效。只需复制代码并粘贴到R中,当我这样做时,它会给出4行。我想你误解了。你的工作对我来说很好。我在问为什么OP的方法失败了。如果我用
args
指定,有什么特色?它在那个时候强制进行评估吗?或者,其他什么?在这种情况下,在这个问题下发表你的评论会更有意义。非常感谢!!您的解决方案也很有效,而且非常独特!!在RStudio社区交叉发布:
library(ggplot2)
plot_func4 <- function(i) {
   p <- ggplot() + xlim(0,i) + xlab("x")
   for (i in 1:i) {
     p <- p + 
        geom_function(fun = parse(text = sprintf("function(x) %d*x", i))[[1]])
   }
   print(p)
 }
plot_func4(4)