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
答案 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))
这给出了:
使用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")