R ggplot:在facet中使用group-variable分组的boxplot

时间:2016-01-12 13:04:05

标签: r ggplot2

我想要一个分组的箱形图。问题是y变量 第一个 n 因子级别和第二个 m 因子级别之间存在很大差异。 似乎有三种解决方案:

  1. 创建两个单独的图表并将它们与共享图例组合。
  2. 在一个图表中创建两个不同的y轴
  3. 使用构面网格。
  4. 由于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")
    

    Example

1 个答案:

答案 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

enter image description here

请注意facet_wrap()公式的语法/顺序。