11

I would like to know if there is a way to let ggplot draw its grid lines in front of the plotted data. As far as I know, I can format almost everything easily by using theme() which works well so far. However, I don't find the option in which order the elements are drawn. I could introduce additional lines to the plot which need to be formatted (coordinates, line groups, etc.) beforehand. Sounds more complicated as it need to be. So I hope, I can modify the plot-grid itself to do the job.

An example of how I am usually plotting the data frame sf.df of the loaded shapefile sf:

(ggplot(sf.df, aes(x=long, y=lat))
+ geom_polygon(data=sf.df, aes(group=group, fill=NFK))
+ theme(panel.grid.major=element_line(colour="black"))
+ coord_map(xlim=c(7.08, 7.14), ylim=c(50.93, 50.96))
)

Thank you in advance!

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
Florian R. Klein
  • 1,375
  • 2
  • 15
  • 32
  • 3
    You aren't going to be able to do this via `theme`. I would think you'd just need two extra geom's, one `geom_hline` and one `geom_vline`. – joran Sep 27 '13 at 15:08
  • Ok, I have to rely on these both then. They work well when everything is set up in a self-made plotting function. The ticks have to be adjusted accpordingly and the grid in background must be invisible. Thank you for pointing me in the seemingly least painful direction :) – Florian R. Klein Sep 27 '13 at 16:17
  • 3
    This question already has an anwser here: https://stackoverflow.com/questions/33989595/overlay-grid-rather-than-draw-on-top-of-it/ ; basically: `theme(panel.ontop=TRUE, panel.background = element_rect(fill = NA))` – AF7 Feb 19 '18 at 11:27

1 Answers1

12

As @joran suggested, using geom_hline and geom_vline is defenitely a solution. Simple define the yintercept and xintercept respectively like so:

...
+ geom_vline(xintercept=seq(7.08, 7.14, by=0.01))
+ geom_hline(yintercept=seq(50.93, 50.96, by=0.01))
...
Florian R. Klein
  • 1,375
  • 2
  • 15
  • 32