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")
#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))
Thanks.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With