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
419 views
in Technique[技术] by (71.8m points)

r - Include space for missing factor level used in fill aesthetics in geom_boxplot

I am trying to draw a box and whisker plot in R. My code is below. At the moment, because I only have data for two months in one of the two sites, the bars are wider for that site (because the third level of month is dropped).

Instead, I would like the same pattern of boxes for site A as there is for site B (i.e. with space for an empty box on the right-hand side). I can easily do this with drop=TRUE when I only have one factor but do not seem to be able to do it with the "filling" factor.

Month=rep(c(rep(c("Jan","Feb"),2),"Mar"),10)
Site=rep(c(rep(c("A","B"),each=2),"B"),10)
factor(Month)
factor(Site)
set.seed(1114)
Height=rnorm(50)
Data=data.frame(Month,Site,Height)
plot = ggplot(Data, aes(Site, Height)) +
       geom_boxplot(aes(fill=Month, drop=TRUE), na.rm=FALSE)
plot
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is a solution, which is based on creating fake data:

Firstly, a new row is added to the data frame. It contains a data point for the non-existing combination of factor levels (Mar and A). The value of Height has to be outside the range of the real Height data.

Data2 <- rbind(Data, data.frame(Month = "Mar", Site = "A", Height = 5))

Then, the plot can be generated. Since the fake data should not be visible, the y axis limits have to be modified with coord_cartesian and the range of the original Height data.

library(ggplot2)
ggplot(Data2, aes(Site, Height)) +
  geom_boxplot(aes(fill = Month)) +
  coord_cartesian(ylim = range(Data$Height) + c(-.25, .25))

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

...