Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

r - Shade background of a ggplot chart using geom_rect with categorical variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...