【问题标题】:Shaded polygons in R with linear constraintsR中具有线性约束的着色多边形
【发布时间】:2013-01-17 17:25:07
【问题描述】:

我有 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')

感谢您的帮助!

编辑:从pmin 函数中删除最后一个y5 就可以了:

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

【问题讨论】:

  • 我想我自己发现了错误。由于我将该区域限制在正象限中,因此对 las 线进行小修正就可以了。我更新了我原来的帖子。
  • 好问题@notrockstar。您是否尝试过对可行区域进行着色?
  • 我不知道任何可以为半平面着色的图形函数,但当然可以模拟将一些坐标放在范围之外。您仍然认为这是一个悬而未决的问题吗?
  • @DWin,我通过geom_area 破解了它。你能为我结束这个问题吗? (我认为我没有此选项可用)。谢谢!
  • 你有答案,你可以发帖,合适的间隔后你可以接受。它与带有否定含义的“关闭”不同,...更好,因为它可以供其他人学习。

标签: r ggplot2 polygon


【解决方案1】:

我的问题在于最后一个变量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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    相关资源
    最近更新 更多