R中的阴影多边形具有线性约束

时间:2013-01-17 17:25:07

标签: r ggplot2 polygon

我有6个线性约束。我知道如何通过手工和r找到解决这个问题的方法。我正在寻找一种简单的方法来获得可行区域的插图。

我尝试ggplot2这样做没有取得任何成功。

以下是约束:x1 >= 0, x2 >= 0, x2 <= 10x2 <= 12 - 2/5 * x1x2 <= 18 - x1x2 <= 18 - x1

require(ggplot2)

# x2 <= 12 - 2/5*x1
fun1 = function(x1){
     x2 = 12 - 2/5*x1
     return(x2)
}

# x2 <= 18 - x1
fun2 = function(x1){
    x2 = 18 - x1
    return(x2)
}

# x2 = 44 - 3*x1
fun3 = function(x1){
    x2 = 44 - 3*x1
    return(x2)
}

x1 = seq(0,20)
mydf = data.frame(x1, fun1(x1), fun2(x1),fun3(x1),rep(10,length(x1)))
names(mydf) = c('x1','y1','y2','y3','y4')
mydf$y5 = rep(0,length(x1))

p0 = ggplot(mydf, aes(x = x1)) + 
     coord_cartesian(ylim=c(0,10),xlim = c(0,20))+                      
     geom_line(aes(y = y1), colour = 'blue') +
     geom_line(aes(y = y2), colour = 'green') +
     geom_line(aes(y = y3), colour = 'red') +
     geom_line(aes(y = y4), colour = 'purple') +
     geom_line(aes(y = y5), colour = 'black')

p0 +  geom_area(aes(y = pmin(y1,y2,y3,y4,y5)), fill = 'gray60')

感谢您的帮助!

编辑:从y5函数中移除最后pmin可以解决问题:

 p0 +  geom_area(aes(y = pmin(y1,y2,y3,y4,y5)), fill = 'gray60')

1 个答案:

答案 0 :(得分:0)

我的问题出现在最后一个变量y5中。从pmin函数中删除它就可以了。

p0 = ggplot(mydf, aes(x = x1)) + 
    coord_cartesian(ylim=c(0,10),xlim = c(0,20))+                      
    geom_line(aes(y = y1), colour = 'blue') +
    geom_line(aes(y = y2), colour = 'green') +
    geom_line(aes(y = y3), colour = 'red') +
    geom_line(aes(y = y4), colour = 'purple') +
    geom_line(aes(y = y5), colour = 'black')

p0 +  geom_area(aes(y = pmin(y1,y2,y3,y4)), fill = 'gray60')