如何仅删除某些facet标签?

12
使用facet_wrap,是否可以仅删除某些facet标签? 在以下示例中,我希望将Species标签仅出现在每行的第一列中。我知道可以使用labeller函数,但不知道如何更改单个标签。
data(iris)
library(tidyr)
library(ggplot2)

dat <- iris %>%
  gather(var, val, Sepal.Length:Petal.Width) 

ggplot(dat) +
  geom_point(aes(x = 1, y = val)) +
  facet_wrap(Species~var)

enter image description here


尝试更改labeller参数吧。我刚看到你在帖子中提到了它。我的错! - NelsonGon
2个回答

9

这并不完美,但我还是希望发布它,希望它比没有更好。

使用 as_labeller()labeller() 可能会得到你所需的结果。

更新

最简单的解决方案是将 Speciesvar 拆分成两个 labellers 函数。

facet_labeller_top <- function(variable, value) {
  c(
    "Setosa", 
    "",
    "",
    "",
    "Versicolor", 
    "",
    "",
    "",
    "Virginica", 
    "",
    "",
    ""
  )
}

facet_labeller_bottom <- function(variable, value) {
  c(
    "Petal.Length", 
    "Petal.Width",
    "Sepal.Length",
    "Sepal.Width",
    "Petal.Length", 
    "Petal.Width",
    "Sepal.Length",
    "Sepal.Width",
    "Petal.Length", 
    "Petal.Width",
    "Sepal.Length",
    "Sepal.Width"
  )
}

结果:

ggplot(dat) +
  geom_point(aes(x = 1, y = val)) +
  facet_wrap(Species~var, labeller = labeller(Species=as_labeller(facet_labeller_top),
                                              var = as_labeller(facet_labeller_bottom)))

在此输入图片描述

数据示例:

library(tidyr)
library(ggplot2)

dat <- iris %>%
  gather(var, val, Sepal.Length:Petal.Width) 

为什么我会看到这个错误:Error in labeller(Species = as_labeller(facet_labeller_top), var = as_labeller(facet_labeller_bottom)) : unused arguments (Species = as_labeller(facet_labeller_top), var = as_labeller(facet_labeller_bottom)) - CrunchyTopping
1
你使用的是哪个版本的 ggplot2?在 3.2.1 上目前可以工作。如果仍然无法运行,请尝试使用干净的环境。 - RLave
1
谢谢!这是一个版本问题,更新解决了它。 - CrunchyTopping

1

我不确定我是否理解得很好,但我会尝试:

您可以使用facet_grid而不是facet_wrap

这是代码:

data(iris)
library(tidyr)
library(ggplot2)

dat <- iris %>%
  gather(var, val, Sepal.Length:Petal.Width) 

ggplot(dat) +
  geom_point(aes(x = 1, y = val)) +
  facet_grid(Species~var)

这是结果: 在此输入图像描述

4
谢谢,但这不是我想要的。正如我所说的,我希望物种标签只出现在每行图例的第一列中。 - erc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接