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.
答案 0 :(得分: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")
答案 1 :(得分: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)
答案 2 :(得分:7)
至少对于ggplot2版本2.0.0。如果您将strip.text.x=
或strip.text.y=
设置为element_blank()
,则会删除文本和特定轴的背景。
a + theme(strip.text. = element_blank())
答案 3 :(得分: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)
答案 4 :(得分:2)
在ggplot2版本3.0.0中,它可以按预期工作。
theme(strip.background.x = element_blank())
现在是有效的主题元素名称。
引用https://github.com/tidyverse/ggplot2/releases/tag/v3.0.0:
小错误修复和改进
令人发指
您现在可以使用以下方式分别设置水平和垂直条的背景样式: strip.background.x和strip.background.y主题设置(#2249)。
可以在以下位置找到基础功能请求:https://github.com/tidyverse/ggplot2/issues/2249