plot small region of a large polygon map in ggplot2

冷暖自知 提交于 2020-02-17 06:34:13

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/18323832/plot-small-region-of-a-large-polygon-map-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!