0

I have the following code to plot some data using boxplot. I am looking to know how to plot some background color in the graph. For instance, it will be very good if I could plot grey color background between group 1 and 2. And dark grey color between group 16 and 18. I am appreciate any help. Regards.

dados <- read.table(text =  'subj var   time    group 
1:  0.9995127   PT  0
2:  0.9994366   PT  0
3:  0.9997657   PT  0
4:  0.9996991   PT  0
5:  0.9938514   T1  1
6:  0.9985952   T1  1
7:  0.9989975   T1  1
8:  0.9988476   T1  1
9:  0.9884567   T2  2
10: 0.998   T2  2
11: 0.9900545   T2  2
12: 0.9973228   T2  2
65: 0.9818935   POT1    16
66: 0.9196845   POT1    16
67: 0.8605142   POT1    16
68: 0.8620914   POT1    16
69: 0.9878192   POT2    17
70: 0.9826672   POT2    17
71: 0.9640381   POT2    17
72: 0.8976091   POT2    17
73: 0.9907579   POT3    18
74: 0.9922122   POT3    18
75: 0.9808981   POT3    18
76: 0.8988121   POT3    18', header = T)
library(ggplot2)
library(dplyr)
dados$group <- as.factor(dados$group)
head (dados)
p<-ggplot(dados, aes(x=group, y=var)) + geom_boxplot()
p + scale_x_discrete(breaks=c("0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22"),labels=c("PT","T01", "T02","T03","T04","T05","T06","T07","T08","T09","T10","T11","T12","T13","T14","T15","POT1","POT2","POT3","POT4","POT5","POT6","POT7"))
markus
  • 25,843
  • 5
  • 39
  • 58

1 Answers1

0

Is this close to what you are looking for?

(Assumes you have done the dados data frame post-processing you have above)

dados <-
  dados %>%
  mutate(
    xstart = as.factor(c(rep(1, nrow(.) / 2), rep(16, nrow(.) / 2))),
    xend = as.factor(c(rep(2, nrow(.) / 2), rep(18, nrow(.) / 2))),
    ystart = -Inf,
    yend = Inf
  )

p <-
  ggplot(dados, aes(x = group, y = var)) +
  theme_bw() +
  geom_rect(
    aes(
      xmin = xstart,
      xmax = xend,
      ymin = ystart,
      ymax = yend,
    ),
    fill = c(rep("gray90", nrow(dados) / 2), rep("gray80", nrow(dados) / 2))
  ) +
  geom_boxplot() +
  scale_x_discrete(
    breaks = as.character(c(0:2, 16:18)),
    labels = c("PT", "T01", "T02", "POT1", "POT2", "POT3")
  )
p

Although, the darker gray, compromises a bit the visibility of the whiskers, at least in this case.