Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

r - How can I suppress the vertical gridlines in a ggplot2 plot?

I am building a bar chart for which bars suffice as indications of horizontal (x) placement, so I'd like to avoid drawing the superfluous vertical gridlines.

I understand how to style the minor and major gridlines in opts(), but I can't for the life of me figure out how to suppress just the vertical gridlines.

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)
  )

At this point, it's looking like I'm going to have to suppress all of the gridlines and then draw them back in with geom_hline(), which seems like kind of a pain (also, it's not entirely clear how I can find the tick/major gridline positions to feed to geom_hline().)

Any thoughts would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of ggplot2 0.9.2, this has become much easier to do using "themes." You can now assign themes separately to panel.grid.major.x and panel.grid.major.y, as demonstrated below.

#   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" ) 
    )

The result of this example is quite ugly looking, but it demonstrates how to remove the vertical lines while preserving the horizontal lines and x-axis tick-marks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...