R函数绘制带阴影的不等式图

3

假设我有一组不等式:

  -2x + y <= -3
1.25x + y <= 2.5
        y >= -3

我可以将信息总结如下:

mat <- matrix(c(-2, 1, 1.25, 1, 0, 1), nrow = 3, byrow = TRUE)
dir <- c("<=", "<=", ">=")
rhs <- c(-3, 2.5, -3)

我编写了以下函数来绘制不等式:
plot(0, 0, xlim = c(-1, 5), ylim = c(-4, 1))
plot_ineq <- function(mat, dir, rhs, xlow, xhigh){
  line <- list()
  for(i in 1:nrow(mat)){
    if(mat[i, 2] > 0){
      line[[i]] <- sapply(seq(xlow, xhigh, 0.1), function(x) (rhs[i] - mat[i, 1] * x)/mat[i, 2])
    }else if(mat[i, 2] < 0){
      line[[i]] <- sapply(seq(xlow, xhigh, 0.1), function(x) (rhs[i] - mat[i, 1] * x)/mat[i, 2])
      if(dir[i] == ">="){
        dir[i] = "<="
      }else dir[i] = ">="
    }
    lines(seq(xlow, xhigh, 0.1), line[[i]])
  }
}

plot_ineq(mat = mat, dir = dir, rhs = rhs, xlow = -1, xhigh = 5)

enter image description here

我有两个问题:(1)如何绘制一个空白的图表,而不需要在那里放置(0,0)点?(2)如何根据dir对应的区域进行着色?我应该尝试ggplot2吗?
我只是想着色上述不等式描述的区域,而不是(0,0)所在的位置。

(1) plot(0, 0, type = "n", etc) 绘制(0,0),类型为“n”,等等。 - Rui Barradas
plot(NULL, xlim = c(-1, 5), ylim = c(-4, 1)) - G5W
1个回答

3

1) 改变最后一个不等式的方向与其他的一致,然后使用 gMOIP 中的 plotPolytope 函数绘制多面体图形。

library(gMOIP)
mat <- matrix(c(-2, 1, 1.25, 1, 0, -1), nrow = 3, byrow = TRUE)
rhs <- c(-3, 2.5, 3)

argsFaces <- list(argsGeom_polygon = list(fill = "blue"))
plotPolytope(mat, rhs, argsFaces = argsFaces)

给予(图像后续)

screenshot

2) 上述使用ggplot2图形,但如果您更喜欢经典图形,则可以使用上文中的mat和rhs:

library(gMOIP)

cp <- cornerPoints(mat, rhs)
cp <- cp[chull(cp), ]  # chull gives indices of convex hull in order
plot(cp, type = "n")
polygon(cp, col = "blue")

# not shown but to add lines run this too
for(i in 1:nrow(cp)) {
  ix <- if (i < nrow(cp)) i + 0:1 else c(i, 1)
  b <- diff(cp[ix, 2]) / (d <- diff(cp[ix, 1]))
  if (abs(d) < 1e-5) abline(v = a <- cp[i, 1])
  else abline(a = a <- cp[i, 2] - b * cp[i, 1], b = b)
}

提供(在图片后继续)

screenshot

3) 请注意,CRAN上有一个名为intpoint的存档软件包,可用于绘制可行域和直线的边界。它有一个限制,即它是硬编码的,只能在-1到5之间显示X和Y轴,尽管将其推广可能不难。使用方式如下(未显示输出),其中mat、rhs和cp来自上文。

library(intpoint)

intpoint:::show2d(mat, rhs, c = numeric(2))
polygon(cp, col = "blue")

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