我想要一个分组的箱形图。问题是y变量 第一个 n 因子级别和第二个 m 因子级别之间存在很大差异。 似乎有三种解决方案:
由于1.和2.看起来很麻烦,我以为我会给出一个镜头。 问题是,在每个子图中显示所有因子级别。 下面的例子说明了这个问题。
library(ggplot2)
mtcars$carb.bin <- mtcars$carb > 2
mtcars$hp[mtcars$carb > 2] <- 10*mtcars$hp[mtcars$carb > 2]
ggplot(mtcars, aes(carb, hp)) + geom_boxplot(aes(fill = factor(carb))) +
facet_wrap(carb.bin~ ., scales = "free")
答案 0 :(得分:2)
你的facet_wrap()的语法令人困惑ggplot2(好吧,反正我;-)) 来自?facet_wrap:
facets:公式或字符向量。使用单面 公式,'~a + b'或字符向量'c(“a”,“b”)'。
我得到了
ggplot(mtcars, aes(carb, hp)) + geom_boxplot(aes(fill = factor(carb))) +
facet_wrap(carb.bin~., scales = "free")
#Error in layout_base(data, vars, drop = drop) :
# At least one layer must contain all variables used for facetting
#and no plot
ggplot(mtcars, aes(carb, hp)) + geom_boxplot(aes(fill = factor(carb))) +
facet_wrap(~carb.bin, scales = "free")
#produces desired plot, add arg ncol=1 to have one facet above the other
请注意facet_wrap()公式的语法/顺序。