Home > Back-end >  Annotating a rectangle in R with ggplot2 for a graph in log scale
Annotating a rectangle in R with ggplot2 for a graph in log scale

Time:12-16

I'm trying to annotate a rectangle in R through ggplot2 for a graph that is in log scale. Here's the annotate layer I am adding:

annotate("rect",xmin=293.3, xmax=312, ymin=-Inf, ymax=Inf, fill='gray')

Of course, I understand the negative infinity is causing problems since it's a log scale and there is no negative value. Since I am pre-specifying my limits on the y-scale, anyone have any thoughts on how to create a 'negative infinity' to infinity rectangle using this method or another method?

CodePudding user response:

R gives log(0) as -Inf, so you can use ymin = 0 to generate -Inf when logged.

Demonstration on built-in data:

ggplot(mtcars, aes(x = wt, y = mpg))  
  annotate("rect", xmin = 2, xmax = 4, ymin = 0, ymax = Inf, fill = 'gray')  
  geom_point()  
  scale_y_continuous(trans = "log") 

enter image description here

  • Related