6
votes

This is my dataset example:

df <- data.frame(group = rep(c("group1","group2","group3", "group4", "group5", "group6"), each=3),
                 X = paste(letters[1:18]),
                 Y = c(1:18))

As you can see, there are three variables, two of them categorical (group and X). I have constructed a line chart using ggplot2 where the X axis is X and Y axis is Y.

I want to shade the background using the group variable, so that 6 different colors must appear.

I tried this code:

ggplot(df, aes(x = X, y = Y)) +
  geom_rect(xmin = 0, xmax = 3, ymin = -0.5, ymax = Inf,
            fill = 'blue', alpha = 0.05) +
  geom_point(size = 2.5)

But geom_rect() only colorize the area between 0 and 3, in the X axis.

I guess I can do it manually by replicating the the geom_rect() so many times as groups I have. But I am sure there must be a more beautiful code using the variable itself. Any idea?

3

3 Answers

8
votes

To get shading for the entire graph, geom_rect needs the xmin and xmax locations for all the rectangles, so these need to be provided by mapping xmin and xmax to columns in the data, rather than hard-coding them.

ggplot(df, aes(x = X, y = Y)) +
  geom_rect(aes(xmin = X, xmax = dplyr::lead(X), ymin = -0.5, ymax = Inf, fill = group), 
            alpha = 0.5) +
  geom_point(size = 2.5) +
  theme_classic()

enter image description here

1
votes

Here is one way:

df2 <- df %>% mutate(Xn=as.numeric(X))

ggplot(df2) +
  geom_rect(aes(xmin=Xn-.5, xmax=Xn+.5, ymin=-Inf, ymax=Inf, fill = group), alpha=0.5, stat="identity") +
  geom_point(aes(x = Xn, y = Y), size = 2.5) + scale_x_continuous(breaks=df2$Xn, labels=df2$X)

enter image description here

1
votes

This will get you close - need to add a couple columns to your data frame. Using dplyr here.

df <- df %>%
  group_by(group) %>%
  mutate(xmin = sort(X)[1],
         xmax = sort(X, decreasing = T)[1])

ggplot(df, aes(x = X, y = Y)) +
  geom_point(size = 2.5) + 
  geom_rect(aes(xmin=xmin, xmax = xmax, fill = group), ymin = -0.5, ymax = Inf,
            alpha = 0.05)