2015-10-14 24 views
1

幾個月前,我需要刪除由ggplot2分面圖生成的一個條。我發現,有人已經問this question,答案工作得很好:刪除一個軸上的strip.background:沒有圖層

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

今天,我試圖重新生成一些數字,用這個代碼,它沒有工作讓我吃驚。顯然,使用ggplotGrob進行grob,修改其內容並將其轉換回ggplot2對象不再有效。

我對如何在這裏繼續有點無知。關於爲什麼這段代碼不再工作的任何想法?

我懷疑包gridExtra可能是罪魁禍首。在我的工作機器上,這個代碼的工作原理是,這個軟件包版本是0.9.1,但是在我的筆記本電腦中,它不工作,我有2.0.0。由於版本之間的差距很大,我不知道可能與此問題有關的更改。

回答

3

更新設置strip.text.xstrip.text.yelement_blank()完全去除條。

library(ggplot2) 

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

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

原始 的一點要注意:ggplot grobs不能轉化回GGPLOT2對象。但是ggplot grobs可以被做成像ggplot2對象一樣。

另一點:在您提供的鏈接中,查看Baptiste解決方案的解決方案列表。它較少依賴ggplot grob的結構。

library(ggplot2) 

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

library(grid) 

# To remove the strip but keep the space 
g <- ggplotGrob(a) 
keep <- !grepl("strip-r", g$layout$name) 
g$grobs <- g$grobs[keep] 
g$layout <- g$layout[keep, ] 
grid.newpage() 
grid.draw(g) 

# To remove the strip and the space 
g = g[, -which(!keep)] 
grid.newpage() 
grid.draw(g) 

爲了使GROB表現得更像一個ggplot對象:

# A print method for the plot 
print.ggplotgrob <- function(x) { 
    grid.newpage() 
    grid.draw(x) 
} 
class(g) = c("ggplotgrob", class(g)) 

g 
ggsave("plotGrob.png", g) 

OR包起來的功能:

strip.remover = function(plot, strip) { 
    g <- ggplotGrob(plot); dev.off() 
    if(!(strip == "t" | strip == "r")) stop("strip must be either 't' or 'r'") 

    keep <- !grepl(paste0("strip-", strip), g$layout$name) 
    g$grobs <- g$grobs[keep] 
    g$layout <- g$layout[keep, ] 

    class(g) <- c("ggplotgrob", class(g)) 
    g 
} 

# A print method for the plot 
print.ggplotgrob <- function(x) { 
    library(grid) 
    grid.newpage() 
    grid.draw(x) 
    } 


# Try it out 
gtplot <- strip.remover(a, "t") 
gtplot 
ggsave("grob.png", gtplot) 

strip.remover(a, "r") 
strip.remover(a, "wrong") 
+0

出色答卷。那麼,在未來版本的ggplot(> 1.0.1)中,沒有ggplot類? – YuppieNetworking

+0

不完全。目前,'ggsave'檢查一個'ggplot'對象。 ggplot grob(即'ggplotGrob(a)')之後的對象是gtable對象,但不是ggplot對象,因此ggsave失敗。在ggplot的下一個版本中,ggsave將保存gtables。 –