plot small region of a large polygon map in ggplot2
Asked Answered
C

1

15

I have a shapefile which I fortified and plotted in ggplot2 using geom_polygon. How can I plot only a small region of this map?

My full map looks fine, but my small region is messed up.

Here is a working example: This small shapefile can be obtained from:

http://www.mappinghacks.com/data/TM_WORLD_BORDERS_SIMPL-0.2.zip

#read data
spf<-readOGR(getwd(),"TM_WORLD_BORDERS_SIMPL-0.2")
spf@data$id<-rownames(spf@data)

#fortify
spf1<-fortify(spf,region="id")

#full plot
ggplot(spf1)+geom_polygon(aes(long,lat,group=group),colour="grey90")

fullplot

#subset plot #this is messy since polygons are broken
ggplot(spf1)+geom_polygon(aes(long,lat,group=group),colour="grey90")+
scale_x_continuous(limits = c(-2, 2))+
scale_y_continuous(limits = c(50, 51))

enter image description here

Thanks.

Cheyenne answered 19/8, 2013 at 22:0 Comment(1)
Oh sorry. Forgot to declare the libraries. require(rgdal) require(ggplot2)Cheyenne
S
30

The limits argument in scale_x_... and scale_y... sets the limits of the scale. Any values outside these limits are not drawn (the underlying data is dropped). This includes elements (such as a polygon) which may only be partially outside these limits.

If you want to zoom the plot in by setting the limits on the coordinates, then use the xlim and ylim arguments to a coord_.... function, From ?coord_cartesian

Setting limits on the coordinate system will zoom the plot (like you're looking at it with a magnifying glass), and will not change the underlying data like setting limits on a scale will.

In your case you have a map, and you can use coord_map, which will project your data using a map projection.

eg

ggplot(spf1, aes(x=long,y=lat,group=group)) + 
  geom_polygon(colour  = 'grey90') +
  coord_map(xlim = c(-2, 2),ylim = c(50, 51))

enter image description here

Squama answered 19/8, 2013 at 23:14 Comment(2)
An additional comment is that, the coord_map needs coordinates as longitude-latitude or it needs a specific projection to be specified. For UTM coordinates, its better to use coord_cartesian.Cheyenne
Any ideas about how to use this together with coord_fixed?Augmentation

© 2022 - 2024 — McMap. All rights reserved.