How to change a SpatialPointsDataFrame into SpatialPolygonsDataFrame in R to use it after in ggplot2?

人盡茶涼 提交于 2019-12-03 15:45:46

ggplot does not work with spatial objects like shape files or raster images. You need to convert them into data.frames.

In case you're working with SpatialPointsDataFrame, this is as simple as:

mapdata <- data.frame(yourshapefile)

# now create the map
  ggplot() +  geom_point( data= mapdata, aes(x=long, y=lat), color="red")

In case you're working with SpatialPolygonsDataFrame, you need to fortify the object, like this:

yourshapefile_df <- fortify(yourshapefile, region ="id")

# now create the map
  ggplot() + geom_point(data= yourshapefile_df, aes(x=long, y=lat, group=group), color="red")

This answer comes from ZevRoss webpage, a very useful source for spatial analysis using R.

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