R ggplot背景色boxplot

时间:2018-11-21 16:43:22

标签: r ggplot2 boxplot

我有一个像这样的数据框:

value = runif(n = 1000) 
type = rep(c("a","b","c","d"),250) 
type2 = rep(c("a","b"),500) 
number = sample(1:4, 1000, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
feature = c(rep("small",500),rep("big",500)) 
allResults <- data.frame(value,type,type2,number,feature)

我想通过 type2 值为箱形图的背景着色。如果我使用fill和col,则不是很清楚。我认为如果可能的话,背景颜色更直观。

library("ggplot2")
ggplot(allResults, aes(y=value, x=type)) + geom_boxplot(alpha=.3, aes(fill = type,col=type2)) +
  ggtitle("comparison") + facet_grid(feature ~ number) +
  theme(legend.position = "bottom",axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks =  seq(0, 1, by = 0.05),limits = c(0,1))

这是我目前的结果:

enter image description here 我已经看到可以使用 geom_rect()为背景着色,但是我不知道如何应用。

1 个答案:

答案 0 :(得分:2)

您可以使用geom_rect并设置部门。我最初将ab作为您的rects因素,但要匹配type中的颜色,只需将其设置为ac

value = runif(n = 1000) 
type = rep(c("a","b","c","d"),250) 
type2 = rep(c("a","b"),500) 
number = sample(1:4, 1000, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
feature = c(rep("small",500),rep("big",500))
nFac <- 4 # define number of factors (types) here
rects <- data.frame(xmin = head(seq <- seq(0.5, nFac + .5, 1), -1), 
                  xmax = tail(seq, -1), rect_type = c("a", "c")) #set your divisions here

allResults <- data.frame(value,type,type2,number,feature, rects)

ggplot(allResults, aes(y=value, x=type)) + geom_boxplot(aes(fill = type, col=type2)) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, fill = rect_type), alpha = 0.009) +
  ggtitle("comparison") + facet_grid(feature ~ number) +
  theme(legend.position = "bottom",axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks =  seq(0, 1, by = 0.05),limits = c(0,1))

enter image description here