简体   繁体   English

R ggplot:在构面中使用组变量的分组箱线图

[英]R ggplot: grouped boxplot using group-variable in facet

I'd like to have a grouped boxplot. 我想要一个分组的箱线图。 The problem is that the y-variable has large differnces between the first n factor levels and the second m factor levels. 问题在于,y变量在前n个因子水平和第二个m因子水平之间有很大的差异。 Three solutions seem possible: 三种解决方案似乎是可能的:

  1. Create two seperate graphs and combine them with a shared legend. 创建两个单独的图,并将它们与共享图例组合。
  2. Create two different y-axes in one graph 在一张图中创建两个不同的y轴
  3. Use facet grid. 使用构面网格。

Since 1. and 2. appear to be cumbersome, I thought I'd give 3. a shot. 由于1.和2.看起来很麻烦,我想我应该试试3。 The problem is, that in each subplot all factor level show up. 问题是,在每个子图中都会显示所有因子水平。 The example below illustrates the issue. 下面的示例说明了该问题。

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")

例

Your syntax for facet_wrap() is confusing ggplot2 (well, me anyway ;-) ) From ?facet_wrap: 您对facet_wrap()的语法令人困惑ggplot2(好吧,无论如何,我还是;-))来自?facet_wrap:

facets: Either a formula or character vector. 方面:公式或字符向量。 Use either a one sided formula, '~a + b', or a character vector, 'c("a", "b")'. 使用单侧公式'〜a + b'或字符向量'c(“ a”,“ b”)'。

I get 我懂了

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

在此处输入图片说明

Note the syntax/order of terms for your facet_wrap() formula. 请注意facet_wrap()公式的语法/术语顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM