2012-03-19 64 views
2

此問題之前已被問過,但答案並不總是清楚或複雜。我希望新版本的ggplot2能夠帶來更簡單的解決方案。消除垂直線ggplot

如何在不消除軸刻度或標籤的情況下消除ggplot的垂直線?這對條形圖來說真的很棒,因爲它可以消除圖形中不必要的干擾。

下面是一些示例代碼,以幫助討論:

library(ggplot2) 
set.seed(10) 
CO3 <- data.frame(id=1:nrow(CO2), CO2[, 2:3], 
      outcome=factor(sample(c('none', 'some', 'lots', 'tons'), 
      nrow(CO2), rep=T), levels=c('none', 'some', 'lots', 'tons'))) 
CO3 
x <- ggplot(CO3, aes(x=outcome)) + geom_bar(aes(x=outcome))+ 
    facet_grid(Treatment~Type, margins='Treatment', scales='free') 
x + theme_bw() + opts(axis.text.x=theme_text(angle= 45, vjust=1, hjust= 1)) 

回答

4

試試這個,redifining guide_grid。

該解決方案是從Cookbook for R

# Save the original definition of the guide_grid 
guide_grid_orig <- ggplot2:::guide_grid 

# Create the replacement function 
guide_grid_no_vline <- function(theme, x.minor, x.major, y.minor, y.major) { 
    x.minor <- setdiff(x.minor, x.major) 
    y.minor <- setdiff(y.minor, y.major) 

    ggname("grill", grobTree(
    theme_render(theme, "panel.background"), 
    if(length(y.minor) > 0) theme_render(
     theme, "panel.grid.minor", name = "y", 
     x = rep(0:1, length(y.minor)), y = rep(y.minor, each=2), 
     id.lengths = rep(2, length(y.minor)) 
    ), 
    if(length(y.major) > 0) theme_render(
     theme, "panel.grid.major", name = "y", 
     x = rep(0:1, length(y.major)), y = rep(y.major, each=2), 
     id.lengths = rep(2, length(y.major)) 
    ) 
    )) 
} 
# Set the environment to be the same as original 
environment(guide_grid_no_vline) <- environment(ggplot2:::guide_grid) 

# Assign the function inside ggplot2 
assignInNamespace("guide_grid", guide_grid_no_vline, ns="ggplot2") 

# Draw the plot with the redefined guide_grid 
ggplot(CO3, aes(x=outcome)) + 
    geom_bar(aes(x=outcome))+ 
    facet_grid(Treatment~Type, margins='Treatment', scales='free') + 
    theme_bw() + 
    opts(axis.text.x=theme_text(angle= 45, vjust=1, hjust= 1)) 

# Restore the original guide_grid function so that it will draw all gridlines again 
assignInNamespace("guide_grid", guide_grid_orig, ns="ggplot2") 
+0

我已經做了,但隨後你遇到麻煩的時候,你讓天秤是免費的。我改變了上面的代碼以反映這一點。我不明確的道歉。 – 2012-03-19 22:57:57

+0

找到了一本關於R – EDi 2012-03-19 23:10:34

+0

作品的烹飪書的解決方案。我忘了檢查R食譜網站。我喜歡那個網站。 – 2012-03-19 23:55:07