【问题标题】:Plot color of values based on where they fall on a 1:1 line - R根据它们落在 1:1 线上的位置绘制值的颜色 - R
【发布时间】:2015-11-06 18:34:49
【问题描述】:

如何根据数据点高于或低于 1:1 线来设置数据点的颜色?

对垂直或水平线(abline)执行此操作非常简单,但对于 1:1 线如何执行此操作?

以下是水平线的做法:

x <- c(2,4,6,8,10)
y <- c(2,4.9,5,9,12)
df <- cbind(x,y)

plot(df[,1], df[,2], xlim=c(0,15), ylim=c(0,15), pch = 21,
     bg =ifelse(df[,2]<=5,"black","red"), col = "black",  cex = 1.5, 
     cex.axis = 1.4, cex.lab = 1.4, xlab = "x", ylab = "y")
abline(h=c(5.0),lty=2)

如何为 1:1 的线做到这一点,其中:

abline(0, 1)

【问题讨论】:

    标签: r graphics plot


    【解决方案1】:

    只需测试x &gt; y 或等效的y &lt;= x

    plot(df[,1], df[,2], xlim=c(0,15), ylim=c(0,15), pch = 21,
         bg =ifelse(df[,2] <= df[,1],"black","red"), col = "black",  cex = 1.5, 
         cex.axis = 1.4, cex.lab = 1.4, xlab = "x", ylab = "y")
    abline(0, 1)
    

    【讨论】:

    • 天哪。很简单。非常感谢@BondedDust!
    • 对@jeremycg 的提示:我认为+(y &lt; x) 有一定的优雅。那是我对您当前删除的答案的赞成票。
    【解决方案2】:

    下面的解决方案将根据它们与 abline 的距离来绘制点颜色。只需计算与 abline 的偏差,然后将其转换为颜色渐变并在 plot 中的 col 参数中使用:

    x <- c(2,4,6,8,10)
    y <- c(2,4.9,5,9,12)
    deviation <- abs(y-x)
    rbPal <- colorRampPalette(c('blue','red'))
    data_col=rbPal(10)[as.numeric(cut(deviation,breaks = 10))]
    df <- cbind(x,y,deviation)
    plot(x, y, xlim=c(0,15), ylim=c(0,15), pch = 21, col=data_col, bg=data_col)
    abline(0, 1)
    

    【讨论】:

    • 这是根据它们与线的距离来着色点,而不是它们是在线的上方还是下方,不是吗?不管怎样,使用bg=data_col 可能看起来不错!
    • 是的。感谢您的推荐。完成!
    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多