How can I use different background color each x value in ggplot?

依然范特西╮ 提交于 2019-12-12 04:07:06

问题


I want to create a boxplot using ggplot library in R. What I want is that set various background color to each x value such as a following image. I cannot find any option for changing bgcolor of each x axis. Only thing I found is for changing entire background color such as 'theme_bw()' option

On first, fourth, fifth x axis, bgcolor is blue. However, there is no value on second, third, sixth x axis, so I want to set red color as bgcolor.

Thanks for your time!


回答1:


Maybe you can build up something on this toy example:

nFac <- 6; nDat <- 10
df <- data.frame(x = gl(nFac, nDat), 
                 y = runif(nFac * nDat))
rec <- data.frame(xmin = head(seq <- seq(0.5, nFac + .5, 1), -1), 
                  xmax = tail(seq, -1), 
                  alpha = c(.5, 0, 0, .5, .5, 0))
library(ggplot2)
ggplot() +
  scale_x_discrete(seq_len(nFac)) +
  geom_rect(data = rec, 
            aes(xmin = xmin, 
                xmax = xmax, 
                alpha = alpha), 
            ymin = -Inf, 
            ymax = Inf, 
            fill = "lightblue",
            colour = "blue",
            size = 2) +
  geom_boxplot(data = df, 
               aes(x = x, y = y)) +
  theme(panel.background = element_rect(fill = "pink"),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank()) +
  guides(alpha = FALSE)



来源:https://stackoverflow.com/questions/25260148/how-can-i-use-different-background-color-each-x-value-in-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!