user212645
user212645

Reputation: 31

How do I plot constraints in R

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

Upvotes: 2

Views: 2431

Answers (1)

tchakravarty
tchakravarty

Reputation: 10954

Update:

You can use geom_polygon to shade the constraint sets. With linear constraints, the edges of the constraint set are easy to compute.

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))

This gives:

enter image description here


Use stat_function. Here is a simple example:

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 There are some enhancements that you can make, like shading the area under the constraint, and to add labels to the constraint lines.

Upvotes: 3

Related Questions