【问题标题】:A loop or something else for plotting using curve() in R在 R 中使用 curve() 进行绘图的循环或其他东西
【发布时间】:2017-04-12 01:35:36
【问题描述】:

我正在尝试以任意 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)

【问题讨论】:

    标签: r for-loop plot


    【解决方案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)
        }
    }
    

    【讨论】:

    • 谢谢,是否可以先绘制最高的一个,然后再绘制另外两个?
    • 谢谢,颜色变化,我应该定义一个单独的向量吗?
    • 是的。您可以使用颜色定义一个矢量,然后将其与col=color_vector[i] 一起使用
    • for (i in 1:10) plot(rnorm(10))
    • spadarian,我可以在提问之前给你发一个 R 文件吗,这是一个循环问题,一切正常,除非我想为每个“i”获取一个 png 文件,png 文件来了空白?
    猜你喜欢
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2016-09-12
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多