You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让geom_function适配两步积分函数以替代循环绘图?

问题描述

我原本通过定义函数、用for循环计算积分结果后绘制出了积分值随参数a变化的曲线,但想避免使用循环,直接用geom_function实现可视化却无法运行,求正确写法。

原代码如下:

fun <- function(a, x) {
  output <- a*dlnorm(a, 2.72 - x, 0.52)
  return(output)
}

fun2 <- function(x) {
  output2 <- integrate(fun, lower = 0, upper = 200, x = x)
  return(output2)
}

a <- seq(-5, 5, .1)

list <- list()

for(ai in 1:length(a)){
  list[[ai]] <- fun2(a[[ai]])
}

list %>% 
  map(pluck, "value") %>% 
  unlist() %>% 
  bind_cols(a) %>% 
  ggplot(aes(x = `...2`, y = `...1`)) + 
  geom_line()

尝试的错误代码:

ggplot() + 
  geom_function(fun = fun2) + 
  xlim(-5, 5)
解决方案

你的代码跑不起来有两个核心问题:

  • integrate()返回的是带value字段的列表,但geom_function要求函数直接返回数值向量
  • 原fun2的参数搞反了——你要画的是积分值随a变化的曲线,所以fun2该接收a当参数,而非x

按下面的方式修改就能正常运行:

  1. 重写fun2,让它直接返回积分的数值结果:
fun2 <- function(a) {
  # 被积函数是关于x的,把a作为参数传给fun,取integrate返回的value值
  integrate(fun, lower = 0, upper = 200, a = a)$value
}
  1. 调用geom_function时直接用修正后的fun2:
ggplot() + 
  geom_function(fun = fun2) + 
  xlim(-5, 5) +
  labs(x = "a", y = "积分值")

这样生成的曲线和你原来用for循环得到的完全一致,还省去了循环的麻烦。

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:22:39