user2386786
user2386786

Reputation: 735

Widen geom_rect()-rectangle in ggplot2 on discrete scale

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.

Upvotes: 2

Views: 1123

Answers (2)

Rfanatic
Rfanatic

Reputation: 2282

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

Upvotes: 1

caldwellst
caldwellst

Reputation: 5956

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

Upvotes: 0

Related Questions