【问题标题】:R ggplot: grouped boxplot using group-variable in facetR ggplot:使用组变量的分组箱线图
【发布时间】:2016-01-12 13:04:04
【问题描述】:

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

  1. 创建两个单独的图表并将它们与共享图例组合。
  2. 在一张图中创建两个不同的 y 轴
  3. 使用分面网格。

由于 1. 和 2. 看起来很麻烦,我想我会试一试 3.。 问题是,在每个子图中,所有因子水平都出现了。 下面的例子说明了这个问题。

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

【问题讨论】:

  • 尝试 facet_wrap(~carb.bin, scales = "free") 对我有用。

标签: r ggplot2


【解决方案1】:

您的 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() 公式的语法/术语顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 2023-04-03
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多