Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a background grid using ggplot2?

Tags:

r

ggplot2

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()
    )
like image 517
user338714 Avatar asked Nov 17 '10 02:11

user338714


People also ask

How do you make a background blank in ggplot2?

The default theme of a ggplot2 graph has a grey background color. You can easily and quickly change this to a white background color by using the theme functions, such as theme_bw() , theme_classic() , theme_minimal() or theme_light() (See ggplot2 themes gallery).

How do I change the gridline color in R?

To change the color of gridlines of a ggplot2 graph in R, we can use theme function with panel. grid. major and panel.

Which Ggplot function should be called to change chart elements such as the panel background color or the presence of grid lines?

The function theme() is used to control non-data parts of the graph including : Line elements : axis lines, minor and major grid lines, plot panel border, axis ticks background color, etc.


2 Answers

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())
like image 134
kohske Avatar answered Oct 19 '22 12:10

kohske


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)))
like image 1
Maiasaura Avatar answered Oct 19 '22 11:10

Maiasaura