我有一个类似的问题,以前针对条形图讨论过,但缺少框形图的解决方案:如果缺少数据,则geom_bar的宽度一致
我想按小组制作箱形图。但是,某些组的数据可能会丢失,从而导致具有丢失组的箱线图的宽度增加。
我尝试指定geom_boxplot(width = value)或geom_boxplot(varwidth = F),但这不起作用。
另外,如Barplots示例所建议,我尝试NA为缺少的数据组添加值。Boxplot仅跳过缺少的数据,并扩展boxplot的宽度。我得到了警告:
Warning messages:
1: Removed 1 rows containing non-finite values (stat_boxplot).
Run Code Online (Sandbox Code Playgroud)
虚拟示例:
# library
library(ggplot2)
# create a data frame
variety=rep(LETTERS[1:7], each=40)
treatment=rep(c("high","low"),each=20)
note=seq(1:280)+sample(1:150, 280, replace=T)
# put data together
data=data.frame(variety, treatment , note)
ggplot(data, aes(x=variety, y=note, fill=treatment)) +
geom_boxplot()
Run Code Online (Sandbox Code Playgroud)
如果每个组都有值,则箱线图具有相同的宽度:
删除1组的值:
# subset the data to have a missing data for group:
data.sub<-subset(data, treatment != "high" | variety != "E" )
windows(4,3)
ggplot(data.sub, aes(x=variety, y=note, fill=treatment)) +
geom_boxplot()
Run Code Online (Sandbox Code Playgroud)
缺少数据的箱形图比另一个宽:
有没有办法保持箱形图的宽度恒定?
我们可以利用中的preserve参数position_dodge。
从 ?position_dodge
保留:躲避应该保留一个位置上所有元素的总宽度还是单个元素的宽度?
ggplot(data.sub, aes(x=variety, y=note, fill=treatment)) +
geom_boxplot(position = position_dodge(preserve = "single"))
Run Code Online (Sandbox Code Playgroud)