如何在R中找出包围原点的直线约束区域及可视化?
直线约束区域可视化与相关问题
核心需求
需要可视化由数据框中**截距(Intercept)和斜率(Slope)**定义的多条直线所围成的、包含原点(0,0)(可修改为指定点(a,b))的区域。直线数量可变,部分直线因其他直线约束更强而冗余,需忽略这类冗余直线,找出包围目标点的约束直线交点,并用这些交点绘制凸包(convex hull),且方案需适配更大规模的数据框。
示例数据框
df <- data.frame("Line" = c("A", "B", "C", "D", "E", "F"), "Intercept" = c(4, 3, -2.5, -1.5, -5, -.5), "Slope" = c(-1, 1, 2.4, -.6, -.8, .6))
示例直线绘制代码(ggplot2)
ggplot(data = df) + geom_vline(xintercept = 0) + geom_hline(yintercept = 0) + geom_abline(mapping = aes(intercept = Intercept, slope = Slope), colour = "red") + coord_cartesian(xlim = c(-6, 6), ylim = c(-6, 6))
核心问题
如何识别包围目标点的约束直线(自动过滤冗余直线),并计算这些直线的交点,同时保证方案可适配大规模数据框?
附加问题
geom_abline没有类似geom_line的group美学映射,如何在ggplot2中基于斜率截距或两点绘制可标识的直线?
更新说明
为将多边形中心改为指定点(a,b)而非原点,修改了@AllanCameron的innermost函数,代码如下:
innermost <- function(slopes, intercepts, a, b) { meetings <- function(slopes, intercepts) { meets_at <- function(i1, s1, i2, s2) { ifelse(s1 - s2 == 0, NA, (i2 - i1)/(s1 - s2)) } xvals <- outer(seq_along(slopes), seq_along(slopes), function(i, j) { meets_at(intercepts[i], slopes[i], intercepts[j], slopes[j]) }) yvals <- outer(seq_along(slopes), seq_along(slopes), function(i, j) { intercepts + slopes * meets_at(intercepts[i], slopes[i], intercepts[j], slopes[j]) }) cbind(x = xvals[lower.tri(xvals)], y = yvals[lower.tri(yvals)]) } xy <- meetings(slopes, intercepts) xy[,1] <- xy[,1] - a xy[,2] <- xy[,2] - b is_cut <- function(x, y, slopes, intercepts, a, b) { d <- sqrt(x^2 + y^2) slope <- y / x xvals <- (intercepts + slopes*a - b) / (slope - slopes) yvals <- xvals * slopes + (intercepts + slopes*a - b) ds <- sqrt(xvals^2 + yvals^2) any(d - ds > 1e-6 & sign(xvals) == sign(x) & sign(yvals) == sign(y)) } xy <- xy[sapply(seq(nrow(xy)), function(i) { !is_cut(xy[i, 1], xy[i, 2], slopes, intercepts, a, b) }),] xy <- xy[order(atan2(xy[,2], xy[,1])),] xy[,1] <- xy[,1] + a xy[,2] <- xy[,2] + b as.data.frame(rbind(xy, xy[1,])) }
内容的提问来源于stack exchange,提问作者nico.sch
相关产品推荐
相关产品推荐

