How do I plot constraints in R

时间:2016-10-19 13:37:10

标签: r constraints linear-programming constraint-programming

I have to plot constraints in R and it's very new to me. Please could someone give me some help.

x1 + 2*x2 <= 100

3x1 + x2 <= 75

Many thanks

1 个答案:

答案 0 :(得分:2)

更新

您可以使用geom_polygon为约束集着色。使用线性约束,约束集的边缘易于计算。

library(ggplot2)

ggplot(data_frame(x = c(0, 100)), aes(x = x)) + 
  stat_function(fun = function(x) {(100 - x)/2}, aes(color = "Function 1")) + 
  stat_function(fun = function(x) {(75 - 3*x) }, aes(color = "Function 2")) + 
  theme_bw() + 
  scale_color_discrete(name = "Function") + 
  geom_polygon(
    data = data_frame(
      x = c(0, 0, 100, Inf),
      y = c(0, 50, 0, 0)
    ),
    aes(
      x = x, y = y, fill = "Constraint 1"
    ),
    inherit.aes = FALSE, alpha = 0.4
  ) + 
  geom_polygon(
    data = data_frame(
      x = c(0, 0, 25, Inf),
      y = c(0, 75, 0, 0)
    ),
    aes(
      x = x, y = y, fill = "Constraint 2"
    ),
    inherit.aes = FALSE, alpha = 0.4
  ) + 
  scale_fill_discrete(name = "Constraint Set") + 
  scale_y_continuous(limits = c(0, 100))

这给出了:

enter image description here

使用stat_function。这是一个简单的例子:

ggplot(data_frame(x = c(0, 100)), aes(x = x)) + 
  stat_function(fun = function(x) {(100 - x)/2}, aes(color = "Function 1")) + 
  stat_function(fun = function(x) {(75 - 3*x) }, aes(color = "Function 2")) + 
  theme_bw() + 
  scale_color_discrete(name = "Function")

enter image description here 您可以进行一些增强,例如在约束下着色区域,以及向约束线添加标签。