下面是一些代码ported from Matlab来计算段之间的交集。如果将其应用于x轴(固定)和每对连续点之间,则会得到一个新坐标列表,指示您的geom_line
与x轴之间的交点。由此可以很容易地遮蔽相关的多边形。请注意,我没有正确测试移植的Matlab代码。
![enter image description here](https://i.stack.imgur.com/PQzNz.png)
## Ported from Matlab to R
## Copyright (c) 2010, U. Murat Erdem
## All rights reserved.
## http://www.mathworks.com/matlabcentral/fileexchange/27205
lineSegmentIntersect <- function(XY1, XY2){
n_rows_1 <- nrow(XY1)
n_cols_1 <- ncol(XY1)
n_rows_2 <- nrow(XY2)
n_cols_2 <- ncol(XY2)
stopifnot(n_cols_1 == 4 && n_cols_2 == 4)
nc <- n_rows_1 * n_rows_2
X1 <- matrix(XY1[,1], nrow=nc, ncol=1)
X2 <- matrix(XY1[,3], nrow=nc, ncol=1)
Y1 <- matrix(XY1[,2], nrow=nc, ncol=1)
Y2 <- matrix(XY1[,4], nrow=nc, ncol=1)
XY2 <- t(XY2)
X3 <- matrix(XY2[1,], nrow=nc, ncol=1)
X4 <- matrix(XY2[3,], nrow=nc, ncol=1)
Y3 <- matrix(XY2[2,], nrow=nc, ncol=1)
Y4 <- matrix(XY2[4,], nrow=nc, ncol=1)
X4_X3 <- X4-X3
Y1_Y3 <- Y1-Y3
Y4_Y3 <- Y4-Y3
X1_X3 <- X1-X3
X2_X1 <- X2-X1
Y2_Y1 <- Y2-Y1
numerator_a <- X4_X3 * Y1_Y3 - Y4_Y3 * X1_X3
numerator_b <- X2_X1 * Y1_Y3 - Y2_Y1 * X1_X3
denominator <- Y4_Y3 * X2_X1 - X4_X3 * Y2_Y1
u_a <- numerator_a/denominator
u_b <- numerator_b/denominator
INT_X <- X1 + X2_X1 * u_a
INT_Y <- Y1 + Y2_Y1 * u_a
INT_B <- (u_a >= 0) & (u_a <= 1) & (u_b >= 0) & (u_b <= 1)
PAR_B <- denominator == 0
COINC_B <- (numerator_a == 0 & numerator_b == 0 & PAR_B)
data.frame(x=INT_X[INT_B], y=INT_Y[INT_B])
}
set.seed(123)
x <- sort(runif(50, -10, 10))
y <- jitter(sin(x), a=2)
n <- length(x)
xy1 <- matrix(c(-10, 0, 10, 0), ncol=4)
xy2 <- cbind(x[-n], y[-n], x[-1], y[-1])
test <- lineSegmentIntersect(xy1, xy2)
library(ggplot2)
d <- data.frame(x=x, y=y)
d2 <- rbind(d, test)
d2 <- subset(d2[order(d2$x), ], y <=0)
p <- qplot(x, y, data=d, geom="path")
p + geom_ribbon(data=d2, aes(ymin = 0, ymax = y), fill="red")
你能提供运行的代码,即一些示例数据? – ROLO 2012-04-02 09:26:45
我编辑的主要文章这样做。 – 2012-04-02 09:41:21
我想你需要首先计算细分中零的位置。 – baptiste 2012-04-02 10:06:50