在ggplot2中,即使不存在给定的级别组合,我也希望方框图中的方框宽度相等。
例如,在mtcars中,cyl = 8和gear = 4不存在,这导致该图中的条形变大:
qplot(data=mtcars, x=as.factor(cyl), y=mpg,
colour=as.factor(gear), geom="boxplot")
Run Code Online (Sandbox Code Playgroud)
对于条形图,使用这些级别组合的NA值填充数据框可以解决问题,而对于箱形图则不能解决问题:
mtcars.fill <- data.frame(cyl=8,gear=4,mpg=NA)
mtcars <- rbind.fill(mtcars,mtcars.fill)
qplot(data=mtcars, x=as.factor(cyl), y=mpg, colour=as.factor(gear), geom="boxplot")
Warning message:
Removed 1 rows containing non-finite values (stat_boxplot).
Run Code Online (Sandbox Code Playgroud)
这导致了完全相同的情节。
stat_boxplot有一个用于na值的参数,但默认设置为不删除NA:
na.rm = FALSE
Run Code Online (Sandbox Code Playgroud)
我能提供的最好的方案是使用facet_grid()
. 这还有一个额外的好处,即geom_point()
图层中的点将与箱线图对齐。
library(ggplot2)
plot1 = ggplot(mtcars, aes(x=factor(gear), y=mpg, colour=factor(gear))) +
geom_boxplot(space=0) +
facet_grid(. ~ cyl, labeller="label_both")
plot2 = plot1 + geom_point()
library(gridExtra)
ggsave(filename="plots.png", plot=arrangeGrob(plot1, plot2, ncol=2),
width=10, height=4, dpi=120)
Run Code Online (Sandbox Code Playgroud)