如何使用ggplot2添加背景网格?

时间:2010-11-17 02:36:26

标签: r ggplot2

我想将背景网格添加到绘图的中心,然后隐藏标准网格线。网格的角点存储在pts数据框中,我尝试使用geom_tile,但它似乎没有使用指定的点。在此先感谢您的帮助。

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

2 个答案:

答案 0 :(得分:7)

您可以手动指定休息时间:

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))
那么,这就是你想要的吗?

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

答案 1 :(得分:1)

不优雅,但这是我想出的快速和肮脏的东西。不幸的是,我无法在某一点停止线路,它只是一路走到边缘。

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