使用R

时间:2017-04-12 01:35:37

标签: r for-loop plot

我试图以3种不同的颜色(例如,红色,绿色,蓝色)绘制3条重叠曲线(请参阅下面的R代码)。我尝试了以下但是没有形状整齐的情节。

这可以轻松地在" R base"?还是有其他一些可能性?

 N  <- c(120, 528, 828)
df1 <- c(3, 3, 3)
df2 <- c(108, 516, 816)
 f  <- c(20, 20, 20) 


## 3 Plots:

Likelihood = curve( df(f, df1, df2, ncp = (x * N) / (1 - x) ) ,
  col = 'red4', lwd = 3, from = 0, to = 1, n = 1e4)

1 个答案:

答案 0 :(得分:1)

使用基本循环,您可以尝试类似:

for(i in 1:length(N)) {
    add <- if(i == 1) FALSE else TRUE
    curve( df(f[i], df1[i], df2[i], ncp = (x * N[i]) / (1 - x) ) ,
           col = i, lwd = 3, from = 0, to = 1, n = 1e4, add=add)
}

不是最漂亮但使用基础知识。你一定要探索ggplot2

为避免某些曲线未完成,您可以先获取每条曲线的值,估算其范围,然后绘制它们。例如:

# function to get the values of each curve
curve_ <- function(x, i) df(f[i], df1[i], df2[i], ncp = (x * N[i]) / (1 - x))

# estimate the values of each curve
curves <- lapply(1:length(N), function(i) {
    x <- seq(0,1,length.out = 1e4)
    curve_(x, i)
})

# estimate the ranges
ranges_ <- sapply(curves, range, na.rm=T)

# plot using the ranges as plotting parameters (ylim)
for (i in 1:length(curves)) {
    if(i == 1) {
        plot(curves[[i]], type='l', col=i, xlim=c(0,length(curves[[i]])), ylim=c(min(ranges_[1,]), max(ranges_[2,])))
    } else {
        lines(curves[[i]], col=i)
    }
}