Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminate strip.background on one axis (ggplot2)

Tags:

r

ggplot2

Many of the theme elements in ggplot2 have a .x or .y only extension to remove/alter something on only one axis. strip.background does not have a strip.background.x equivalent as can be seen below.

How can I remove the text and strip.background from the facet labels on only one axis?

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.
like image 242
Tyler Rinker Avatar asked Sep 28 '13 06:09

Tyler Rinker


4 Answers

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

like image 117
Roland Avatar answered Oct 23 '22 18:10

Roland


At least for the ggplot2 version 2.0.0. if you set the strip.text.x= or strip.text.y= to element_blank() it removes text and the background for particular axis.

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

enter image description here

like image 22
Didzis Elferts Avatar answered Oct 23 '22 19:10

Didzis Elferts


Here's a way to remove the relevant strips,

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)
like image 7
baptiste Avatar answered Oct 23 '22 18:10

baptiste


Same idea but using grid package

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

like image 3
agstudy Avatar answered Oct 23 '22 19:10

agstudy