Dan Strobridge
Dan Strobridge

Reputation: 337

How to use Infinity limits with a transformed scale?

Is there a workaround for when one wants to apply geom_rect to Infinity on the y axis of a ggplot object when a transformation is applied to the y axis?

The code below does not plot the interval rectangles unless you comment out the scale_y_continuous line. When using the transformed scale, I have to put in actual data limits. I could probably write a function to find the min/max of the other data being plotted to avoid hard coding values but I'm looking for something closer to the Inf approach. I tried using NA instead of Inf but no luck.

    library(tidyverse)
    data(economics)

    ints<-data.frame(start=as.Date(paste0(seq(1970,2020,by=10),"-01-01"))) %>% 
      mutate(end=start+1785)

    plt<-ggplot(economics,aes(date,unemploy)) + theme_bw() +
      scale_y_continuous(trans="sqrt") +
      geom_rect(data=ints,inherit.aes=F,aes(xmin=start,xmax=end,ymin=-Inf,ymax=Inf)) + geom_line()

    plt

Upvotes: 1

Views: 939

Answers (1)

TheSciGuy
TheSciGuy

Reputation: 1196

library(tidyverse)
data(economics)

ints<-data.frame(start=as.Date(paste0(seq(1970,2020,by=10),"-01-01"))) %>% 
  mutate(end=start+1785)

plt<-ggplot(economics,aes(date,unemploy)) + theme_bw() +
  scale_y_continuous(trans="sqrt") +
  geom_rect(data=ints,inherit.aes=F,aes(xmin=start,xmax=end,ymin=0,ymax=Inf)) + geom_line()+
  coord_cartesian(ylim=c(2000,20000)) # This will allow you to control how zoomed in you want the plot

plt

enter image description here

Upvotes: 1

Related Questions