How can I plot a continents map with R?

跟風遠走 提交于 2019-11-29 07:01:44

rworldmap has functions for plotting or aggregating data to regional levels including continents.

A simple start that should produce the plot below :

library(rworldmap)
#get coarse resolution world from rworldmap
sPDF <- getMap()  
#mapCountries using the 'continent' attribute  
mapCountryData(sPDF, nameColumnToPlot='continent')

Or for the 7 continents model :

mapCountryData(sPDF, nameColumnToPlot='REGION')

To aggregate your own data from country to regional level look at :

?mapByRegion

Following up on @Andy's answer, you could merge country polygons within each continent like so:

library(rworldmap)
library(rgeos)
library(maptools)
library(cleangeo)  ## For clgeo_Clean()

sPDF <- getMap()
sPDF <- clgeo_Clean(sPDF)  ## Needed to fix up some non-closed polygons 
cont <-
    sapply(levels(sPDF$continent),
           FUN = function(i) {
               ## Merge polygons within a continent
               poly <- gUnionCascaded(subset(sPDF, continent==i))
               ## Give each polygon a unique ID
               poly <- spChFIDs(poly, i)
               ## Make SPDF from SpatialPolygons object
               SpatialPolygonsDataFrame(poly,
                                        data.frame(continent=i, row.names=i))
           },
           USE.NAMES=TRUE)

## Bind the 6 continent-level SPDFs into a single SPDF
cont <- Reduce(spRbind, cont)

## Plot to check that it worked
plot(cont, col=heat.colors(nrow(cont)))

## Check that it worked by looking at the SPDF's data.frame
## (to which you can add attributes you really want to plot on)
data.frame(cont)
#                   continent
# Africa               Africa
# Antarctica       Antarctica
# Australia         Australia
# Eurasia             Eurasia
# North America North America
# South America South America

library(sp) #Load your libraries
library(maptools)
#Download the continents shapefile
download.file("http://baruch.cuny.edu/geoportal/data/esri/world/continent.zip",
              "cont.zip")
#Unzip it
unzip("cont.zip")
#Load it
cont <- readShapeSpatial("continent.shp")
#Plot it
plot(cont,
     col=c("white","black","grey50","red","blue","orange","green","yellow")) 
#Or any other combination of 8 colors

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