93

我正在构建一个条形图,其中条形足以指示水平 (x) 位置,因此我想避免绘制多余的垂直网格线。

我了解如何在 opts() 中设置次要和主要网格线的样式,但我无法终生弄清楚如何仅抑制垂直网格线。

library(ggplot2)

data <- data.frame(x = 1:10, y = c(3,5,2,5,6,2,7,6,5,4))

ggplot(data, aes(x, y)) +
  geom_bar(stat = 'identity') +
  opts(
    panel.grid.major = theme_line(size = 0.5, colour = '#1391FF'),
    panel.grid.minor = theme_line(colour = NA),
    panel.background = theme_rect(colour = NA),
    axis.ticks = theme_segment(colour = NA)
  )

在这一点上,看起来我将不得不压制所有的网格线,然后用 geom_hline() 将它们拉回来,这似乎有点痛苦(而且,我不完全清楚如何找到刻度线/major 网格线位置提供给 geom_hline()。)

任何想法将不胜感激!

4

5 回答 5

191

从 ggplot2 0.9.2 开始,使用“主题”变得更加容易。您现在可以将主题分别分配给 panel.grid.major.x 和 panel.grid.major.y,如下所示。

#   simulate data for the bar graph
data <- data.frame( X = c("A","B","C"), Y = c(1:3) )    

#   make the bar graph
ggplot( data  ) +
    geom_bar( aes( X, Y ) ) +
    theme( # remove the vertical grid lines
           panel.grid.major.x = element_blank() ,
           # explicitly set the horizontal lines (or they will disappear too)
           panel.grid.major.y = element_line( size=.1, color="black" ) 
    )

这个例子的结果看起来很丑,但它演示了如何删除垂直线,同时保留水平线和 x 轴刻度线。

于 2012-01-24T18:32:55.003 回答
28

尝试使用

scale_x_continuous(中断 = NULL)

这将删除所有垂直网格线以及 x 轴刻度线标签。

于 2010-04-21T06:55:49.140 回答
4

这只剩下数据点:

ggplot(out, aes(X1, X2)) + 
    geom_point() + 
    scale_x_continuous(breaks = NULL) + 
    scale_y_continuous(breaks = NULL) + 
    opts(panel.background = theme_blank()) + 
    opts(axis.title.x = theme_blank(), axis.title.y = theme_blank())
于 2011-03-10T02:09:58.580 回答
4

选项1:

data_df <- data.frame(x = 1:10, y = c(3,5,2,5,6,2,7,6,5,4))

ggplot(data_df, aes(x, y)) +
  geom_bar(stat = 'identity') +
  theme(panel.background = element_rect(fill = "white"))

选项 2:

data_df <- data.frame(x = 1:10, y = c(3,5,2,5,6,2,7,6,5,4))
    
ggplot(data_df, aes(x, y)) +
      geom_bar(stat = 'identity') +
      theme(
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.major.y = element_blank(),
        panel.grid.minor.y = element_blank()
      )
于 2020-11-19T20:28:05.130 回答
1

从相关线程复制我的答案,

对于在 2020 年查找此内容的人,我在rdrr.io > removeGrid的 ggExtra 库中找到了 removeGrid 函数形式的解决方案

我已经测试它与 ggplot2 版本 3.3.0 和 ggExtra 版本 0.9 一起使用,给了我没有网格线的轴刻度。

于 2020-07-17T14:48:17.167 回答