r - 使用 ggplot 和 purrr 绘制多条逻辑曲线的推导图

标签 r ggplot2 purrr derivative

数据框“pars”的行包含定义逻辑曲线的两个参数:

library(ggplot2)
library(purrr)

pars <- data.frame(
  diff = c(-1.5, 2.5),
  disc = c(1.2, 2.5)
)

这两条曲线可以像这样用map()和ggplot()绘制。

icc <- function(x) map(
  1:nrow(pars),
  ~ stat_function(fun = function(x)
    (exp(pars$disc[.x]*(x - pars$diff[.x])))/(1 + exp(pars$disc[.x]*(x - pars$diff[.x]))))
)
ggplot(data.frame(x = -5 : 5)) +
  aes(x) +
  icc()

enter image description here

相应的推导可以这样绘制:

disc1 <- 1.2
disc2 <- 2.5
diff1 <- -1.5
diff2 <- 2.5

icc1 <- function(x) (exp(disc1*(x - diff1)))/(1 + exp(disc1*(x - diff1)))
icc2 <- function(x) (exp(disc2*(x - diff2)))/(1 + exp(disc2*(x - diff2)))

info1 <- Deriv(icc1, "x")
info2 <- Deriv(icc2, "x")

ggplot(data.frame(x = -5 : 5)) +
  aes(x) +
  stat_function(fun = info1) +
  stat_function(fun = info2)

enter image description here

但是,我想使用更通用的方法,最好使用 purrr() 进行推导,因为我需要一个用于不同数量曲线的函数。也许有一个使用 pmap() 的解决方案,它可以迭代带有参数的数据帧并将函数和推导应用于每一行。不幸的是,到目前为止我并不走运。我非常感谢任何有用的答案。

最佳答案

一个选项可能如下所示:

  1. 我已将曲线参数放入 data.frame
  2. 利用函数工厂和 pmap 循环参数 df 以创建 icc 函数列表。

其余部分非常简单。

  • 循环函数列表以获取导数。

  • 使用 map 添加stat_function图层。

  • library(ggplot2)
    library(Deriv)
    #> Warning: package 'Deriv' was built under R version 4.1.2
    library(purrr)
    
    df <- data.frame(
      disc = c(1.2, 2.5),
      diff = c(-1.5, 2.5)
    )
    
    icc <- function(disc, diff) {
      function(x) (exp(disc*(x - diff)))/(1 + exp(disc*(x - diff)))
    }
    
    icc_list <- pmap(df, function(disc, diff) icc(disc, diff))
    info_list <- map(icc_list, Deriv, "x")
    
    ggplot(data.frame(x = -5 : 5)) +
      aes(x) +
      map(info_list, ~ stat_function(fun = .x))
    

    编辑合并不同的颜色或......并不是什么大问题,例如您可以使用 purrr::map2 循环遍历 info_list 和颜色向量,为每个函数或导数分配颜色:

    colorVec <- c("red", "blue")
    
    ggplot(data.frame(x = -5 : 5)) +
      aes(x) +
      map2(info_list, colorVec, ~ stat_function(fun = .x, color = .y))
    

    编辑 2 最后,我们可以应用相同的想法来获得像这样的图例,其中我们不将 color 设置为参数,而是将其映射到 color aes 并通过 scale_color_manual 设置颜色:

    colorVec <- c("red", "blue")
    labelsVec <- c("f1", "f2")
    names(colorVec) <- labelsVec
    
    ggplot(data.frame(x = -5 : 5)) +
      aes(x) +
      map2(info_list, labelsVec, ~ stat_function(fun = .x, aes(color = .y))) +
      scale_color_manual(values = colorVec)
    

    enter image description here

    关于r - 使用 ggplot 和 purrr 绘制多条逻辑曲线的推导图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70772445/

    相关文章:

    r - 在 ggplot 中制作圆形线端 - 在情节和图例中

    r - 如何使用 purrr 中的 map 和 dplyr 中的 mutate 来生成 glm 汇总表?

    r - 如何在 r 中处理具有超过 500 万个观测值的数据帧时加速迭代?

    r - 在 R 中将列表拆分为单独的数据框

    r - 计算每行的每周返回 - 应用

    r - 如何从一个范围制作一个序列

    r - 按唯一 ID 填充组的缺失数据

    r - Sourcing 脚本不会将任何输出打印到控制台

    r - 根据ggplot2中类别的比例调整(堆叠)条宽

    r - 使用 ggplot() 在同一图上绘制多个时间序列