Mori
Mori

Reputation: 135

the rectangles color in ggplot using geom_rec

I want to have two rectangles 1- xmin=0.3,xmax=.7, ymin=5, ymax=100 with a bit dark gray 2- xmin=0.3,xmax=.7, ymin=3, ymax=5 with light gray

I used the following but I could not get what I need.

p[[1]] <-ggplot(mat_ind, aes(x = times1, y = mat_ind[,1])) +
  geom_line() +ylab("") +
  xlab("")  + ylim(-6,100)+xlim(0.3,.7)+ theme(panel.grid = element_blank(),
                              axis.title = element_blank(),
                              axis.text.x = element_blank(),
                              plot.margin=unit(c(1,-1,0,0),"cm"))+theme_bw()+ 
  geom_rect(data=mat_ind, inherit.aes=FALSE,
                    aes(xmin=0.3,xmax=.7, ymin=5, ymax=100, fill="gray45"), alpha=0.01 )+
  geom_rect(data=mat_ind, inherit.aes=FALSE,
                    aes(xmin=0.3,xmax=.7, ymin=3, ymax=5, fill= "grey"), alpha=0.01 )

Could you please lead me to do that.

Upvotes: 0

Views: 585

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174546

We don't have your data, but let's create some with the same names:

times1 <- seq(0.3, 0.7, length.out = 100)
mat_ind <- as.data.frame(matrix(cumsum(runif(100)), ncol = 1))

If you want to add specific rectangles as annotations, you should use annotate rather than geom_rect. Otherwise, you are likely to get multiple copies of the rectangles:

library(ggplot2)

ggplot(data = mat_ind, aes(x = times1, y = mat_ind[,1])) +
  geom_line() +
  annotate("rect", xmin = 0.3, xmax = .7, ymin = 5, ymax = 100, 
           fill = "gray45", alpha = 0.5) +
  annotate("rect", xmin = 0.3, xmax = .7, ymin = 3, ymax = 5, fill= "grey", 
            alpha = 0.5) +
  xlab("") +
  ylab("") +
  ylim(-6,100) +
  xlim(0.3,.75) + 
  theme_bw() + 
  theme(panel.grid = element_blank(),
        axis.title = element_blank(),
        axis.text.x = element_blank(),
        plot.margin = unit(c(1, -1, 0, 0), "cm"))

Created on 2020-12-07 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions