【问题标题】:Eliminate vertical lines ggplot消除垂直线ggplot
【发布时间】:2012-04-04 10:58:19
【问题描述】:

以前有人问过这个问题,但答案并不总是很清楚或很复杂。我希望新版本的 ggplot2 能够带来更简单的解决方案。

如何在不消除轴刻度线或标签的情况下仅消除 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))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试这个,重新定义 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")
    

    【讨论】:

    • 我已经这样做了,但是当你让天平空闲时你会遇到麻烦。我更改了上面的代码以反映这一点。我很抱歉没有更清楚。
    • 在 R 的食谱上找到了解决方案
    • 就像一个魅力。我忘了查看 R 食谱网站。我喜欢那个网站。
    • 我必须从它们各自的包中提取guide_grid_no_vline 中的所有函数,但除此之外,这工作得很好。不过,删除几行似乎很麻烦。
    • 感谢上帝,这个解决方案已被更新版本的 ggplot2 淘汰。见stackoverflow.com/a/2680870/322912
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多