half-pass 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

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?

Answer Source

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:


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.

enter image description here

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