【问题标题】:Concise way to draw multiple curves on one plot in R在R中的一个图上绘制多条曲线的简洁方法
【发布时间】:2015-02-07 15:23:46
【问题描述】:

我有 6 个函数,它们变化不大,我想在同一张图上绘制它们的曲线:

myfun1=function(x){y=x/(1-0.01*(1-x))}
myfun2=function(x){y=x/(1-0.05*(1-x))}
myfun3=function(x){y=x/(1-0.1*(1-x))}
myfun4=function(x){y=x/(1-0.2*(1-x))}
myfun5=function(x){y=x/(1-0.3*(1-x))}
myfun6=function(x){y=x/(1-0.5*(1-x))}

plot(myfun1, 0, 10, xlim=c(0,10), ylim=c(0,10))
plot(myfun2, 0, 10, xlim=c(0,10), ylim=c(0,10), add=TRUE)
plot(myfun3, 0, 10, xlim=c(0,10), ylim=c(0,10), add=TRUE)
plot(myfun4, 0, 10, xlim=c(0,10), ylim=c(0,10), add=TRUE)
plot(myfun5, 0, 10, xlim=c(0,10), ylim=c(0,10), add=TRUE)
plot(myfun6, 0, 10, xlim=c(0,10), ylim=c(0,10), add=TRUE)

这给了我一个我想要的带有 6 条曲线的图。但是,有没有更简单的方法来做到这一点,只有几行?唯一改变的是常数 0.01,0.05,... 等等。

我还想要某种图例来表明哪条曲线是理想的方法可以让我做到这一点。

谢谢

【问题讨论】:

    标签: r plot curve-fitting


    【解决方案1】:

    使用返回函数的函数如下:

    f <- function(p) return(function(x){y=x/(1-p*(1-x))})
    plot(0, xlim=c(0,10), ylim=c(0,10), type = "n")
    for (x in c(0.01, 0.05, 0.1, 0.2, 0.3, 0.5))
      plot(f(x), from = 0, to = 10, add = TRUE)
    

    【讨论】:

    • 谢谢@lukeA。我试过plot(f(x), from = 0, to = 10, add = TRUE, col=c("yellow","green","blue","purple","red","orange") 使线条颜色不同,但这只会使所有线条都变黄。有什么想法可以让它们变成不同的颜色吗?
    • 一种使用不同颜色的方法:for (x in cols &lt;- c(0.01, 0.05, 0.1, 0.2, 0.3, 0.5)) plot(f(x), from = 0, to = 10, add = TRUE, col = which(x == cols)).
    • 多次调用plot(..., add=TRUE) 相当丑陋。建议使用单个plot,然后多次调用curvelines
    • @BondedDust imo for (z in c(0.01, 0.05, 0.1, 0.2, 0.3, 0.5)) curve(f(z)(x), 0, 10, add = TRUE) 看起来并没有那么好。还是有更优雅的方式?
    • 我确实认为它更好,因为它使用图形设备上现有的 xlim 和 ylim 值。
    【解决方案2】:

    是的,这可以通过创建函数生成器得到显着改善。我还使用ggplot2 而不是基本plot 以获得更好的可视化效果(完全主观),并根据功能添加图例。

    param    = list(0.01, 0.05, 0.1, 0.2, 0.3, 0.5)
    func_gen = function(u) function(x) x/(1-u*(1-x))
    x        = seq(0,10,by=0.2)
    
    library(plyr)
    library(ggplot2)
    
    df = ldply(param, function(u) data.frame(x=x, y=func_gen(u)(x), variable=as.character(u)))
    
    ggplot(df, aes(x=x, y=y, color=variable)) + geom_point()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      相关资源
      最近更新 更多