使用条件颜色绘制多边形

6

我想要对曲线下的区域进行着色。当y > 0时,该区域应为红色,当y < 0时,该区域应为绿色。

x <- c(1:4)
y <- c(0,1,-1,2,rep(0,4))
plot(y[1:4],type="l")
abline(h=0)

使用ifelse()不起作用:

polygon(c(x,rev(x)),y,col=ifelse(y>0,"red","green"))

到目前为止,我所取得的成就如下:

polygon(c(x,rev(x)),y,col="green")
polygon(c(x,rev(x)),ifelse(y>0,y,0),col="red")

但是红色区域太大了。你有什么想法来获得期望的结果吗?
2个回答

5
如果你想要两种不同的颜色,你需要两个不同的多边形。你可以多次调用多边形函数,或者在你的x和y向量中添加NA值来指示一个新的多边形。R不会为你自动计算交集。你必须自己完成。下面是如何用不同的颜色绘制它的方法。
x <- c(1,2,2.5,NA,2.5,3,4)
y <- c(0,1,0,NA,0,-1,0)

#calculate color based on most extreme y value
g <- cumsum(is.na(x))
gc <- ifelse(tapply(y, g, 
    function(x) x[which.max(abs(x))])>0, 
    "red","green")

plot(c(1, 4),c(-1,1), type = "n")
polygon(x, y, col = gc)
abline(h=0)

输入图像描述

在更一般的情况下,将多边形分成不同的区域可能并不容易。在GIS软件包中,似乎有些支持此类型操作,因为这种操作更为常见。然而,我已经考虑了一个相对简单的多边形情况。

首先,我定义了一个闭包来定义切割线。该函数将取得直线的斜率和截距,并返回我们需要切割多边形所需的函数。

getSplitLine <- function(m=1, b=0) {
    force(m); force(b)
    classify <- function(x,y) {
        y >= m*x + b
    }
    intercepts <- function(x,y, class=classify(x,y)) {
        w <- which(diff(class)!=0)
        m2 <- (y[w+1]-y[w])/(x[w+1]-x[w])
        b2 <- y[w] - m2*x[w]

        ix <- (b2-b)/(m-m2)
        iy <- ix*m + b
        data.frame(x=ix,y=iy,idx=w+.5, dir=((rank(ix, ties="first")+1) %/% 2) %% 2 +1)
    }
    plot <- function(...) {
    abline(b,m,...)
    }
    list(
        intercepts=intercepts,
        classify=classify,
        plot=plot
    )
}

现在,我们将定义一个函数,使用刚刚定义的分割器来实际分割多边形。
splitPolygon <- function(x, y, splitter) {
    addnullrow <- function(x) if (!all(is.na(x[nrow(x),]))) rbind(x, NA) else x
    rollup <- function(x,i=1) rbind(x[(i+1):nrow(x),], x[1:i,])
    idx <- cumsum(is.na(x) | is.na(y))
    polys <- split(data.frame(x=x,y=y)[!is.na(x),], idx[!is.na(x)])
    r <- lapply(polys, function(P) {
        x <- P$x; y<-P$y
        side <- splitter$classify(x, y)
        if(side[1] != side[length(side)]) {
            ints <- splitter$intercepts(c(x,x[1]), c(y, y[1]), c(side, side[1]))
        } else {
            ints <- splitter$intercepts(x, y, side)
        }
        sideps <- lapply(unique(side), function(ss) {
            pts <- data.frame(x=x[side==ss], y=y[side==ss], 
                idx=seq_along(x)[side==ss], dir=0)
            mm <- rbind(pts, ints)
            mm <- mm[order(mm$idx), ]
            br <- cumsum(mm$dir!=0 & c(0,head(mm$dir,-1))!=0 & 
                c(0,diff(mm$idx))>1)
            if (length(unique(br))>1) {
                mm<-rollup(mm, sum(br==br[1]))
            }
            br <- cumsum(c(FALSE,abs(diff(mm$dir*mm$dir))==3))
            do.call(rbind, lapply(split(mm, br), addnullrow))
        })
        pss<-rep(unique(side), sapply(sideps, nrow))
        ps<-do.call(rbind, lapply(sideps, addnullrow))[,c("x","y")]
        attr(ps, "side")<-pss
        ps
   })
   pss<-unname(unlist(lapply(r, attr, "side")))
   src <- rep(seq_along(r), sapply(r, nrow))
   r <- do.call(rbind, r)
   attr(r, "source")<-src
   attr(r, "side")<-pss
   r
}

输入只是像您将传递给多边形一样的xy的值,以及切割器。它将返回一个数据框,其中包含可与polygon一起使用的x和y值。

例如:

x <- c(1,2,2.5,NA,2.5,3,4)
y <- c(1,-2,2,NA,-1,2,-2)

sl<-getSplitLine(0,0)

plot(range(x, na.rm=T),range(y, na.rm=T), type = "n")
p <- splitPolygon(x,y,sl)
g <- cumsum(c(F, is.na(head(p$y,-1))))
gc <- ifelse(attr(p,"side")[is.na(p$y)],  
    "red","green")
polygon(p, col=gc)
sl$plot(lty=2, col="grey")

这对于有斜线的简单凸多边形也适用。这里是另一个例子。
x <- c(1,2,3,4,5,4,3,2)
y <- c(-2,2,1,2,-2,.5,-.5,.5)

sl<-getSplitLine(.5,-1.25)

plot(range(x, na.rm=T),range(y, na.rm=T), type = "n")
p <- splitPolygon(x,y,sl)
g <- cumsum(c(F, is.na(head(p$y,-1))))
gc <- ifelse(attr(p,"side")[is.na(p$y)],  
    "red","green")
polygon(p, col=gc)
sl$plot(lty=2, col="grey")

在此输入图片描述

目前,当多边形的顶点恰好落在切割线上时,情况可能会有点混乱。我将来可能会尝试修正这个问题。


啊,我刚意识到我使用了一个糟糕的例子。因为 y 中有0,多边形的一侧已经在分割线上了。那么没有0的数据怎么办,比如 y <- c(1,-2,2,NA,-1,2,-2)?我不知道需要做出什么样的调整。 - mrub
你们实际上都是凸多边形吗?还是也有凹的情况?我已经快要得到一个更通用的解决方案了,但还有一些恼人的边缘情况。 - MrFlick
我认为我只会有凸多边形。通常情况下,我必须分割绘制的数据,这些数据将仅由凸多边形组成。 - mrub

3

一种更快但不太准确的解决方案是根据分组变量(例如above=red和below=blue)将数据框拆分为列表。这是一个相当不错的解决方法,适用于相对较大的数据集(我会说> 100个元素)。对于较小的块,可能会出现一些不连续性:

x <- 1:100
y1 <- sin(1:100/10)*0.8
y2 <- sin(1:100/10)*1.2
plot(x, y2, type='l')
lines(x, y1, col='red')

df <- data.frame(x=x, y1=y1, y2=y2)

df$pos_neg <- ifelse(df$y2-df$y1>0,1,-1) # above (1) or below (-1) average

# create the number for chunks to be split into lists:
df$chunk <- c(1,cumsum(abs(diff(df$pos_neg)))/2+1) # first element needs to be added`
df$colors <- ifelse(df$pos_neg>0, "red","blue") # colors to be used for filling the polygons
# create lists to be plotted:
l <- split(df, df$chunk) # we should get 4 sub-lists
lapply(l, function(x) polygon(c(x$x,rev(x$x)),c(x$y2,rev(x$y1)),col=x$colors))

如我所说,对于较小的数据集,在正负区域之间发生急剧变化时可能会出现一些不连续性,但如果水平线将这两者区分开来,或者绘制更多的元素,则可以忽略此效果:

results


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接