【问题标题】:Plotting intersections on line graphs in R在 R 中的折线图上绘制交点
【发布时间】:2013-11-12 13:40:29
【问题描述】:

我想使用 R 绘制具有相同 x 值(例如日期)的两个数据系列。我想要在同一张图上的两条线,但是一条比另一条大的线段应该是另一种颜色。举个例子:

x<-c(-5:5)
y1<-x^2-x-10
y2<-(x^3)-(x^2)-(10*x)+2
plot(x,y1,col="blue", ylim=c(-100,100), type="l")
par(new=T)
plot(x,y2,col="green", ylim=c(-100,100), type="l")

y2 大于 y1 的部分为红色。因此,绿线或多或少会在 -3 3 时再次变为红色(我试图发布该图,但我的声誉不够高)。我想开发一些代码,让我可以对任何数据集执行此操作,例如在矩阵中:

xy<-as.matrix(cbind(x,y1,y2))

我怀疑它可以使用forif 循环来完成,但我更喜欢更优雅的解决方案。如果我也可以这样做:Show the intersection of two curves,那就太好了!

非常感谢您的帮助!

【问题讨论】:

    标签: r graph plot intersection


    【解决方案1】:

    这是一个非常基本的解决方案,通过创建几个新变量,使用NA 值来抑制在不需要的区域中绘图:

    y2high <- y2
    y2high[y2high < y1] <- NA
    y2low <- y2
    y2low[y2low > y1] <- NA
    
    plot(x,y1,type='l', col='blue')
    lines(x,y2high,col='red')
    lines(x,y2low,col='green')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2022-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      相关资源
      最近更新 更多