5

Let's say I have a plot generated by this code:

library(ggplot2); ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()

I would like to remove an arbitrary horizontal (or vertical) gridline, perhaps v = 12500 or v = 15000 (or both). I addition, I would like to keep the respective tickmark(s). Is there any relatively easy way to do this?

For the clarity, I do not want to get rid of all minor gridlines, especially not all the gridlines.

Jacko
  • 51
  • 1

1 Answers1

5

You can try something like this, without having to use grid to modify the underlying object.

First we get the coordinates of major/minor

ymajor = ggplot_build(p)$layout$panel_params[[1]]$y.major_source
yminor = ggplot_build(p)$layout$panel_params[[1]]$y.minor_source
yminor = setdiff(yminor,ymajor)

ymajor_cols = ifelse(ymajor == 15000,"transparent","white")
yminor_cols = ifelse(yminor == 12500,"transparent","white")

Then we add to your plot by specifying

ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()+
theme(panel.grid.major.y  = element_line(colour = ymajor_cols),
panel.grid.minor.y  = element_line(colour = yminor_cols))

enter image description here

I would actually prefer specifying the major and minor breaks and specifying them in the plot, the below code gives the same results:

ymajor = c(0,5000,10000,15000)
yminor = c(0,2500,12500,17500)
ymajor_cols = ifelse(ymajor == 15000,"transparent","white")
yminor_cols = ifelse(yminor == 12500,"transparent","white")

ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()+
scale_y_continuous(breaks=ymajor,minor_breaks = yminor)+
theme(panel.grid.major.y  = element_line(colour = ymajor_cols),
panel.grid.minor.y  = element_line(colour = yminor_cols))
StupidWolf
  • 34,518
  • 14
  • 22
  • 47