如何在ggplot2图中抑制垂直网格线?

时间:2010-04-20 19:47:56

标签: r ggplot2

我正在构建一个条形图,其条形图足以作为水平(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()将它们拉回来,这看起来很痛苦(同样,我不知道我怎么能找到要添加到geom_hline()的tick / major网格线位置。)

任何想法都将不胜感激!

6 个答案:

答案 0 :(得分:132)

从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轴刻度标记的同时删除垂直线。

答案 1 :(得分:13)

尝试使用

  

scale_x_continuous(breaks = NULL)

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

答案 2 :(得分:5)

请参阅网格级别编辑以获取其他选项:

https://github.com/hadley/ggplot2/wiki/Editing-raw-grid-objects-from-a-ggplot

答案 3 :(得分: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())

答案 4 :(得分:0)

从相关主题复制我的答案,

对于在2020年进行查询的人们,我在这里的rdrr.io > removeGrid

处从ggExtra库中找到了removeGrid函数形式的解决方案。

我已经测试过它可以与ggplot2版本3.3.0和ggExtra版本0.9一起使用,从而为我提供了没有网格线的轴刻度。

答案 5 :(得分:0)

选项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()
      )