Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot bounding boxes in ggplot?

Tags:

r

ggplot2

I have the coordinates for a rectangular bounding box. Example.

maxlat = 49,minlat = 30,maxlong = -117,minlong = -125

that defines the bounds.

How can I put a box corresponding to this on the US map?

Basically I am looking for a figure like this: enter image description here

I want to put six such boxes to put on one US Map. If I can put a serial number like 1,2,3,4 next to the plots, that would be even better. But just putting the boxes there would also be great.

Addendum:

The US Map was made using this:

usamap <- map_data("state")
ggplot() + 
  geom_polygon( data=usamap, aes(x=long, y=lat,group=group),colour="black", fill="white" )+
  xlab('Longitude')+
  ylab('Latitude')+
  coord_map(projection = "mercator")+
  theme_bw()+
  theme(legend.position = c(.93,.20),panel.grid.major = element_line(colour = "#808080"))+
  ggsave("usmap_blank.png",width=10, height=8,dpi=300)
like image 605
maximusdooku Avatar asked Jan 15 '15 20:01

maximusdooku


1 Answers

You could create a data.frame with the annotation infomation you would like

boxes<-data.frame(maxlat = 49,minlat = 30,maxlong = -117,minlong = -125, id="1")
boxes<-transform(boxes, laby=(maxlat +minlat )/2, labx=(maxlong+minlong )/2)

and then add the boxes and labels as separate layers

usamap <- map_data("state")
ggplot() + 
  geom_polygon( data=usamap, aes(x=long, y=lat,group=group),colour="black", fill="white" )+
  xlab('Longitude')+
  ylab('Latitude')+
  coord_map(projection = "mercator")+
  geom_rect(data=boxes, aes(xmin=minlong , xmax=maxlong, ymin=minlat, ymax=maxlat ), color="red", fill="transparent") + 
  geom_text(data=boxes, aes(x=labx, y=laby, label=id), color="red") + 
  theme_bw()+
  theme(legend.position = c(.93,.20),panel.grid.major = element_line(colour = "#808080"))

enter image description here

You can add rows for as many boxes as you would like in the boxes table.

like image 165
MrFlick Avatar answered Oct 15 '22 22:10

MrFlick