使用ggplot2绘制多条曲线

And*_*son 3 plot r ggplot2

假设我有一个数据框coefs,其中每行包含曲线的模型系数.

coefs <- structure(list(a1 = c(1.22228259789383, 1.2064168157394, 1.09555089661994, 0.943947433470916, 0.883490658557721, 0.46125552320107), d = c(0.385227755933488, 0.457271644919152, 0.340063262461958, 0.305629949064525, 0.42459163183877, 0.425710112988664), g = c(0, 0, 0, 0, 0, 0), u = c(1, 1, 1, 1, 1, 1)), .Names = c("a1", "d", "g", "u"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))
Run Code Online (Sandbox Code Playgroud)

我想使用数据框的每一行基于定义的函数向绘图添加新曲线:(您可以将其识别为2PL项目响应模型)

TWOPL <- function(x,a1,b) {
  1 / (1 + exp(-a1*(x-(b))))
}
Run Code Online (Sandbox Code Playgroud)

基于这个这个问题,我尝试了以下ggplot命令,但得到计算失败的错误:

library(ggplot2)
p <- ggplot(coefs, aes(x = 0))
p + stat_function(fun = TWOPL) + xlim(-5,5)
Run Code Online (Sandbox Code Playgroud)

我知道我需要一种方法来为函数提供各种系数.作为测试,我尝试使用固定参数的函数来创建1条曲线并且它可以工作,例如:

#1 curve based on fixed parameters
TWOPL_copy <- function(x) {
  1 / (1 + exp(-1.22*(x-(.385))))
}

p <- ggplot(data.frame(x = 0), aes(x = 0))
p + stat_function(fun = TWOPL_copy) + xlim(-5,5)
Run Code Online (Sandbox Code Playgroud)

我想知道如何将数据帧的每一行发送到ggplot.理想的下一步是以某种方式区分每条线的颜色.

ali*_*ire 6

虽然您可以调用stat_function每组参数或者通过编程方式调用它,但是自己进行计算更简单:

library(tidyverse)

coefs %>% 
    mutate(curve = letters[row_number()]) %>%    # add curve name
    crossing(x = seq(-5, 5, .1)) %>%    # repeat each row for every occurence of x
    mutate(y = TWOPL(x, a1, d)) %>%    # compute y values
    ggplot(aes(x, y, color = curve)) + 
    geom_line()
Run Code Online (Sandbox Code Playgroud)

以编程方式创建曲线的最简单方法是向stat_function绘图添加调用列表.所有美学都必须反复进行,包括颜色.的x审美必须提供,但如果设置xlim,它不会不管它是什么.

curves <- coefs %>% 
    mutate(curve = letters[row_number()]) %>% 
    pmap(function(...){
             dots <- data_frame(...)
             stat_function(data = dots, aes(0, color = curve), 
                           fun = function(x) TWOPL(x, dots$a1, dots$d), 
                           xlim = c(-5, 5))
    })

ggplot() + curves
Run Code Online (Sandbox Code Playgroud)