使用ggplot2绘制多条曲线 [英] Use ggplot2 to plot multiple curves
问题描述
说我有一个数据框coefs
,其中每一行都包含一条曲线的模型系数.
Say I have a data frame coefs
where each row contains model coefficients for a curve.
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))
我想使用数据框的每一行,根据已定义的函数向图中添加一条新曲线:(您可以将其识别为2PL项目响应模型)
I'd like to use each row of the data frame to add a new curve to the plot based a defined function: (you may recognize it as a 2PL item response model)
TWOPL <- function(x,a1,b) {
1 / (1 + exp(-a1*(x-(b))))
}
基于此和
Based on this and this question I tried the following ggplot command but get the error that computation failed:
library(ggplot2)
p <- ggplot(coefs, aes(x = 0))
p + stat_function(fun = TWOPL) + xlim(-5,5)
我知道我需要一种给函数赋予各种系数的方法.作为测试,我尝试使用具有固定参数的函数创建1条曲线,并且该曲线有效,例如:
I know that I need a way to give the various coefficients to the function. As a test, I tried the function with a fixed parameters to create 1 curve and it works, for example:
#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)
我想知道如何将数据帧的每一行发送到ggplot.理想的下一步是以某种方式区分每行的颜色.
I'm wondering how I might send each row of the data frame to ggplot. An ideal next step would be to differentiate the colors of each line somehow.
推荐答案
尽管您可以为每组参数调用stat_function
,或者可以通过编程方式调用它,但是您自己进行计算会更简单:
While you could call stat_function
for each set of parameters or with some pain call it programmatically, it's simpler to do the calculations yourself:
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()
以编程方式创建曲线的最简单方法是向绘图添加一个stat_function
调用列表.所有美学都必须反复进行,包括颜色.必须提供x
美观度,但是如果设置xlim
,则无关紧要.
The simplest way to create the curves programmatically is to add a list of stat_function
calls to the plot. All aesthetics have to be iterated across, including color. An x
aesthetic must be supplied, but if you set xlim
, it doesn't matter what it is.
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
这篇关于使用ggplot2绘制多条曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!