Kathiravan Meeran
Kathiravan Meeran

Reputation: 450

geom_rect gives empty plot with no rectangle

I would like to get a rectangle box between every point of dawn and dusk. I don't understand why the code below is not giving the desired result

dawn = seq(200, 210, by =  0.5)
dusk = seq(200.5, 210.5, by = 0.5)
night = data.frame("dusk" = dusk, "dawn" = dawn)


ggplot()+
  geom_rect(data = night, aes(xmin = dawn , xmax = dusk ,
                              ymin = -Inf, ymax = Inf),
 fill = "blue", alpha = 0.5, colour = NA)

enter image description here I couldnt see the filled rectangle.

Upvotes: 1

Views: 535

Answers (2)

tjebo
tjebo

Reputation: 23787

You need a y aesthetic. What do you want to plot anyways??

library(ggplot2)
dawn = seq(200, 210, by =  0.5)
dusk = seq(200.5, 210.5, by = 0.5)
night = data.frame("dusk" = dusk, "dawn" = dawn, y = 1)


ggplot(night, aes(dawn, y))+
  geom_rect(data = night, aes(xmin = dawn , xmax = dusk ,
                              ymin = -Inf, ymax = Inf),
            fill = "blue", alpha = 0.5, colour = NA) 

Created on 2021-02-09 by the reprex package (v0.3.0)

Upvotes: 2

drmariod
drmariod

Reputation: 11772

As an alternative, you could define the coordinate system with limits...

ggplot()+
    geom_rect(data = night, aes(xmin = dawn , xmax = dusk ,
                                ymin = -Inf, ymax = Inf),
              fill = "blue", alpha = 0.5, colour = NA) +
    coord_cartesian(ylim=c(0.2,0.8))

In this way it works with Inf as well.

Upvotes: 2

Related Questions