half-pass - 1 year ago 127
R Question

# Shade a region of ggplot where x,y satisfy a constraint

I'd like to generate a

`ggplot`
in which the entire region where X and Y satisfy the following constraint is shaded:

(XY) / (X+Y-1) > 2

What is the best way to do this?

Well, I don't think I could plot the entire region, but how about this: The inequality is equivalent to `y > 2*(x-1)/(x-2)`, so let's find the critical y value for each x and then plot the region where the inequality is satisfied:

``````library(ggplot2)

x = seq(-10,14,0.001)
y = 2*(x-1)/(x-2)
dat = data.frame(x,y)

ggplot(dat) +
geom_ribbon(aes(x, ymin=y, ymax=ifelse(x>2, Inf,-Inf)), fill="blue") +
theme_bw() +
coord_cartesian(ylim=range(-10,14), xlim=c(-10,14),expand=FALSE) +
labs(y="y") +
geom_hline(yintercept=2, colour="red", size=0.5, alpha=0.5)
``````

The horizontal red line shows the critical value that y approaches (which is 2) as the absolute value of x gets large.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download