7

I'd like to add background grid to the center of the plot and then hide the standard gridlines. The corner points of the grid are stored in the pts data frame and I've tried using geom_tile, but it doesn't appear to use the specified points. Thanks in advance for your help.

library(ggplot2)  
pts <- data.frame(
        x=c(170,170,170,177.5,177.5,177.5,185,185,185), 
        y=c(-35,-25,-15,-35,-25,-15,-35,-25,-15))  
ggplot(quakes, aes(long, lat)) + 
    geom_point(shape = 1) + 
    geom_tile(data=pts,aes(x=x,y=y),fill="transparent",colour="black") +
    opts(
        panel.grid.major=theme_blank(),
        panel.grid.minor=theme_blank()
    )
Yuriy Petrovskiy
  • 7,888
  • 10
  • 30
  • 34
user338714
  • 2,315
  • 5
  • 27
  • 36

2 Answers2

8

you can manually specify the breaks:

ggplot(quakes, aes(long, lat)) + geom_point(shape = 1) +
  scale_x_continuous(breaks = c(170, 177.5, 185)) +
  scale_y_continuous(breaks = c(-35, -25, -15)) +
  opts(panel.grid.minor = theme_blank(), 
       panel.grid.major = theme_line("black", size = 0.1))

then, is this what you want?

pts <- data.frame(x=c(170, 170, 170, 170, 177.5, 185), 
                  y=c(-35, -25, -15, -35, -35, -35),
                  xend=c(185, 185, 185, 170, 177.5, 185),
                  yend=c(-35, -25, -15, -15, -15, -15))
ggplot(quakes, aes(long, lat)) + geom_point(shape = 1) + 
   geom_segment(data=pts, aes(x, y, xend=xend, yend=yend)) +
   opts(panel.grid.minor = theme_blank(), 
        panel.grid.major = theme_blank())
kohske
  • 65,572
  • 8
  • 165
  • 155
  • 1
    I'd actually like to have the grid "float" in the background instead (see my example). Thanks though. – user338714 Nov 17 '10 at 13:28
  • This is exactly what I was looking for--thanks. I also found that geom_path would work, but it is quite cumbersome to plot out all of the points along the path: pts <- data.frame(x=c(170,170,170,177.5, 177.5,177.5,185,185,185,177.5,170,170,177.5,185,185,177.5,170), y=c(-35,-25,-15,-15,-25,-35,-35,-25,-15,-15,-15,-25,-25,-25,-35,-35,-35)). – user338714 Nov 17 '10 at 13:59
  • 1
    This no longer works with the current version of ggplot2 (1.0.0), by the way. – Maxim.K Sep 24 '14 at 09:17
1

Not elegant but this is something quick and dirty that I came up with. Unfortunately I can't stop the line at a certain point, it just goes all the way to the edge.

ggplot(quakes, aes(long, lat)) + geom_point(shape = 1)
 + opts(panel.grid.major=theme_blank(),
        panel.grid.minor=theme_blank())
 + geom_vline(aes(xintercept =seq(165,185,by=5)))
 + geom_hline(aes(yintercept=seq(-35,-15,by=5)))
isomorphismes
  • 8,233
  • 9
  • 59
  • 70
Maiasaura
  • 32,226
  • 27
  • 104
  • 108
  • If you are editing a figure such as this for a publication, you can always save as eps, then edit out the extra lines in Adobe Illustrator. That's what I would do. – Maiasaura Nov 17 '10 at 04:13