I have a ggplot2 graph which appears as follows:
Notice that the grid or axis lines do not show through the ribbons. One way of dealing with this is to alte
You could use grid package functionality to extract the grid lines from the plot, and then redraw them, which would avoid some of the manual specification when adding horizontal or vertical lines.
library(ggplot2)
library(grid)
# Draw your plot
ggplot(data.frame(x=sample(1:100),y=sample(1:100)), aes(x=x,y=y))+
geom_point(size=20)
# This extracts the panel including major and minor gridlines
lines <- grid.get("grill.gTree", grep=TRUE)
# Redraw plot without the gridlines
# This is done, as otherwise when the lines are added again they look thicker
last_plot() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
# Navigate to relevant viewport
# To see these use grid.ls(viewports=TRUE)
seekViewport("panel.3-4-3-4")
# Redraw lines
grid.draw(lines$children[-1])
Which produces
Alternatively, if you wanted to automate the adding of the vertical and horizontal lines within ggplot (as in Narendra's answer), but without specifying the breaks manually, you can access their positions using ggplot_build(p), where p is your plot.
It may be worth showing this for a graph with facets. Same procedure, except you select multiple lines and panels, and then just loop through them to draw.
# New plot with facets
ggplot(mtcars, aes(mpg, wt)) + geom_point(size=10) + facet_grid(am~cyl)
gr <- grid.ls(print=FALSE)
# Get the gTree for each of the panels, as before
lines <- lapply(gr$name[grep("grill.gTree", gr$name)], grid.get)
last_plot() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
# Get the names from each of the panels
panels <- gr$name[grep("panel.\\d", gr$name)]
# Loop through the panels redrawing the gridlines
for(i in 1:length(panels)) {
seekViewport(panels[i])
grid.draw(lines[[i]]$children[-1])
}
This will also work for the plots without facts.