0

I want half my chart background to be yellow. I've been thinking that I could definitely use a rectangle to put it under the graph.

ggplot(df2, aes(x=zeitpunkt.faktor, y=weight, group=group, color=group)) + 
  geom_errorbar(aes(ymin=weight-sd, ymax=weight+sd), width=.2) + 
  geom_line() + 
  geom_point() + 
  labs(x="Zeit in Wochen", y = "Gewicht in g") + 
  scale_color_brewer(palette="Paired")+ 
  theme_minimal() + 
  labs(colour="Gruppe") + 
  geom_rect(df2, mapping=aes(xmin=0.5, xmax=7.5, ymin=-Inf, ymax=+Inf), fill="yellow", alpha=0.01, inherit.aes = FALSE)

However, I had the problem that my rectangle lies over the graph and hides it (see picture 1).

Picture 1: rectangle lies over the graph and hides it, right x-axis)

I searched something (and found this here: Refining ggplot R code so annotated rectangle appears behind plot points), changed the order and then got the following error "Discrete value supplied to continuous scale", so I didn't enter my x-variable as factor anymore.

ggplot(df3, aes(x=zeitpunkt, y=weight, group=group, color=group)) + 
  geom_rect(df3, mapping=aes(xmin=-0.5, xmax=13, ymin=-Inf, ymax=+Inf), fill="yellow", alpha=0.01, inherit.aes = FALSE) + 
  geom_line() + 
  geom_point() + 
  geom_errorbar(aes(ymin=weight-sd, ymax=weight+sd), width=.2) + 
  labs(x="Zeit in Wochen", y = "Gewicht in g") + 
  scale_color_brewer(palette="Paired")+theme_minimal() + 
  labs(colour="Gruppe")

Now the rectangle fits, but I only have some numbers on the x-axis and not all, like when using the factor (see picture 2).

Picture 2: right rectangle, false x-axis

My question is: How can I get my rectangle behind the graph and at the same time my x-axis like in the first picture?

Thanks for your help (and sorry for the question, I'm really still a beginner at R)!

GGamba
  • 13,140
  • 3
  • 38
  • 47
tree--frog
  • 11
  • 2
  • 1
    Hard to test it without a reproducible example, but should be something like `scale_x_continuous(breaks=seq(min(zeitpunkt.faktor), max(zeitpunkt.faktor),by=2))` – iod Oct 30 '18 at 14:28
  • 1
    Perfect, it worked, thank you very much! – tree--frog Oct 30 '18 at 15:40

0 Answers0