Home > Net >  Striped background colour on every other x block in ggplot2 in R
Striped background colour on every other x block in ggplot2 in R

Time:12-06

I was referring to enter image description here

Error code: enter image description here

CodePudding user response:

The issue is that the global aesehtitics x, y and color are inherited by each geom layer. As a side effect this means that ggplot2 requires the columns mapped on these aesthetics to be present in the data used for each layer, which is not the case for the geom_rect, i.e. your dataset rec has no columns subcategory, Type 1 Error or Model. To fix that add inherit.aes = FALSE to geom_rect to prevent the global aes to be inherited.

Note: I also removed the expansion of the x scale by adding expand = c(0, 0) to scale_x_discrete.

ggplot(data = d, aes(x = subcategory, y = `Type 1 Error`, color = Model))  
  scale_x_discrete(seq_len(nFac), expand = c(0, 0))  
  geom_rect(
    data = rec,
    aes(
      xmin = xmin,
      xmax = xmax,
      alpha = alpha
    ),
    ymin = -Inf,
    ymax = Inf,
    fill = "lightblue",
    inherit.aes = FALSE
  )  
  geom_errorbar(
    data = d, aes(ymin = LL, ymax = UL),
    width = 0.5, position = "dodge"
  )  
  facet_wrap(~category,
    labeller = as_labeller(\(x) paste("Cor(G\u0079, G\u1D07) =", x)),
    strip.position = "top"
  )  
  theme_classic()  
  theme(
    panel.spacing = unit(0, "lines"),
    plot.title = element_text(hjust = 0.5),
    strip.placement = "outside",
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    legend.position = "none"
  )  
  ggtitle("a. Var(GxE) = 0")  
  xlab("Cor(\u0190\u0079, \u0190\u1D07)")  
  geom_abline(aes(slope = 0, intercept = 0.05), linetype = "dashed")  
  ylim(min, max)

enter image description here

  • Related