13

ggplot2 中的许多主题元素仅具有 .x 或 .y 扩展名,以仅在一个轴上删除/更改某些内容。 strip.background没有strip.background.x等价物,如下所示。

如何strip.background仅在一个轴上删除文本和分面标签?

a <- ggplot(mtcars, aes(mpg, hp)) +
    geom_point() +
    facet_grid(cyl~gear) 

a + theme(strip.text.y = element_blank(), 
    strip.background.x = element_blank())

##     > a + theme(strip.text.y = element_blank(), strip.background.x = element_blank())
##     Error in (function (el, elname)  : 
##       "strip.background.x" is not a valid theme element name.
4

5 回答 5

8
library(ggplot2)
a <- ggplot(mtcars, aes(mpg, hp)) +
  geom_point() +
  facet_grid(cyl~gear) 

strip.remover <- function(ggp, what="x") {
  require(gridExtra)

  zeroGrob <- function() {
    g0 <- grob(name="NULL")
    class(g0) <- c("zeroGrob",class(g0))
    g0
  }

  g <- ggplotGrob(ggp)

  g$grobs <- lapply(g$grob, function(gr) {
    if (any(grepl(paste0("strip.text.", what),names(gr$children)))) {
      gr$children[[grep("strip.background",names(gr$children))]] <- zeroGrob()
      gr$children[[grep("strip.text",names(gr$children))]] <- zeroGrob()
    }
    return(gr)
  }
  )

  class(g) = c("arrange", "ggplot",class(g)) 
  g
}

strip.remover(a, "y")

enter image description here

于 2013-09-28T07:40:57.337 回答
7

这是一种删除相关条带的方法,

library(grid)  # for the grid functions
g <- ggplotGrob(a)
keep <- !grepl("strip-right", g$layout$name)
g$grobs <- g$grobs[keep]
g$layout <- g$layout[keep, ]
grid.newpage()
grid.draw(g)
于 2013-09-28T14:24:00.680 回答
7

至少对于 ggplot2 版本 2.0.0。如果您将strip.text.x=or设置strip.text.y=element_blank()它会删除特定轴的文本和背景。

a + theme(strip.text. = element_blank())

enter image description here

于 2016-01-20T13:20:41.867 回答
3

相同的想法,但使用grid

g <- ggplotGrob(a)
gg <- g$grobs
strip_right.index <- which(grepl('strip-right',g$layout$name))
for(ii in strip_right.index)
  gg[[ii]] <- editGrob(getGrob(gg[[ii]],'strip.back'
                               ,grep=TRUE,global=TRUE)
                       ,gp = gpar(fill=NA))

g$grobs <- gg
grid.draw(g)

enter image description here

于 2013-09-28T07:48:45.250 回答
2

在 ggplot2 3.0.0 版中,这可以按您的预期工作。 theme(strip.background.x = element_blank())现在是一个有效的主题元素名称。

引用自https://github.com/tidyverse/ggplot2/releases/tag/v3.0.0

小错误修复和改进

刻面

You can now style the background of horizontal and vertical strips independently with strip.background.x and strip.background.y theme settings (#2249).

The underlying feature request can be found here: https://github.com/tidyverse/ggplot2/issues/2249

于 2018-08-09T07:54:18.940 回答