r - 如何在保留 x 轴标签的同时抑制 ggplot2 图中的垂直网格线?

标签 r ggplot2

这是 this question, in which I was trying to suppress the vertical gridlines 的后续内容.

学习者提供的解决方案是添加 scale_x_continuous(breaks = NA),但这也有抑制 x 轴标签的副作用。我很高兴用手重新写标签,但我不清楚如何弄清楚标签应该放在哪里。

另一种选择是抑制所有网格线(使用 opts( panel.grid.major = theme_blank()) 或一些类似的),然后只绘制主要的水平网格线。同样,这里的问题是如何找出图中的中断点以提供给 geom_hline()。

所以,基本上,我的选择是:

  • 抑制垂直网格线和 x 轴标签(使用 scale_x_continuous(breaks = NA) )并重新添加 x 轴标签。
  • 抑制所有网格线(使用 opts( panel.grid.major = theme_blank()) )并使用 geom_hline() 添加主要水平网格线。

  • 这里有两个选项:
    library(ggplot2)
    
    data <- data.frame(x = 1:10, y = c(3,5,2,5,6,2,7,6,5,4))
    
    # suppressing vertical gridlines and x-axis labels
    # need to re-draw x-axis labels
    ggplot(data, aes(x, y)) +
      geom_bar(stat = 'identity') +
      scale_x_continuous(breaks = NA) +
      opts(
        panel.grid.major = theme_line(size = 0.5, colour = '#1391FF'),
        panel.grid.minor = theme_blank(),
        panel.background = theme_blank(),
        axis.ticks = theme_blank()
      )
    
    # suppressing all gridlines
    # need to re-draw horizontal gridlines, probably with geom_hbar() 
    ggplot(data, aes(x, y)) +
      geom_bar(stat = 'identity') +
      scale_x_continuous(breaks = NA) +
      opts(
        panel.grid.major = theme_blank(),
        panel.grid.minor = theme_blank(),
        panel.background = theme_blank(),
        axis.ticks = theme_blank()
      )
    

    最佳答案

    由于注释中的代码不能很好地显示,所以我将其作为答案发布。您可以执行类似操作并使用 geom_text() 手动添加标签。 :

    ggplot(data, aes(x, y)) +
            geom_bar(stat = 'identity') +
            scale_x_continuous(breaks = NA) +
            opts(
                    panel.grid.major = theme_line(size = 0.5, colour = '#1391FF'),
                    panel.grid.minor = theme_blank(),
                    panel.background = theme_blank(),
                    axis.ticks = theme_blank()
            )+
            geom_text(aes(label = x, y = -.3))
    

    关于r - 如何在保留 x 轴标签的同时抑制 ggplot2 图中的垂直网格线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684966/

    相关文章:

    无法加载 R lapack 例程

    r - 如何使用 ggplot2 添加背景网格?

    r - 在 R ggplot 中控制矩形 geom_ribbon

    r - ggvis:交互图

    r - ggplot2:使图例中的符号与图中的符号匹配

    r - geom_map 所有子区域颜色相同

    r - 通过 Shiny 将图片上传到 knitr 文档

    R ggplot2 : boxplots with significance level (more than 2 groups: kruskal. 测试和 wilcox.test 成对)和多个方面

    r - 如何增加ggplot中*旋转* y轴上文本和标题之间的距离?

    r - 有没有办法找出函数的返回类型?