Home > database >  Widen geom_rect()-rectangle in ggplot2 on discrete scale
Widen geom_rect()-rectangle in ggplot2 on discrete scale

Time:12-15

I have the following code:

library(tidyverse)

exp<-data.frame(a=c(10,30,80,100),b=c("A","B","C","D"))

exp %>%
  ggplot(aes(b,a)) 
  geom_rect(aes(xmin="A",xmax="D",ymin=0,ymax=50,fill="red"))  
  geom_point()

enter image description here

As you can see, the values for "A" and "D" are on the borders of the rectangle provided by geom_rect(). How can I get geom_rect() to start at x=0 and use the entire width of the plot? I want to use errorbars in my dataset and they are halfway outside the rectangle this way.

CodePudding user response:

Just set xmin and xmax to -Inf and Inf respectively.

exp %>%
  ggplot(aes(b,a))  
  geom_rect(aes(xmin=-Inf,xmax=Inf,ymin=0,ymax=50,fill="red")) 
  geom_point()

enter image description here

CodePudding user response:

I had to modify your exp$a in order to start in 0

  exp<-data.frame(a=c(0,30,80,100),b=c("A","B","C","D"))
    exp %>% ggplot(aes(b,a)) 
      geom_rect(aes(xmin="A",xmax="D",ymin=0,ymax=100,fill="red")) 
      geom_point() 
       scale_x_discrete(labels=c("A", "B", "C", "D"), expand=c(0, 0))   
       scale_y_continuous(expand = c(0, 50))

enter image description here

  • Related