使用带分类变量的geom_rect来阴影ggplot图表的背景

ant*_*sor 3 r ggplot2

这是我的数据集示例:

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

如您所见,有三个变量,其中两个是分类的(groupX).我使用ggplot2构建了一个折线图,其中X轴是X,Y轴是Y.

我想使用group变量对背景进行着色,因此必须出现6种不同的颜色.

我试过这段代码:

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)
Run Code Online (Sandbox Code Playgroud)

但是,geom_rect()只有在着色区域之间03,在X轴.

我想我可以通过复制geom_rect()我所拥有的那么多次来手动完成.但我确信必须有一个更漂亮的代码使用变量本身.任何的想法?

eip*_*i10 5

要获得整个图形的着色,geom_rect需要所有矩形的位置xminxmax位置,因此需要通过映射xminxmax数据中的列来提供这些,而不是对它们进行硬编码.

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


thc*_*thc 1

这是一种方法:

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述