Choropleth world map

后端 未结 2 1298
半阙折子戏
半阙折子戏 2021-02-01 11:51

I have read so many threads and articles and I keep getting errors. I am trying to make a choropleth? map of the world using data I have from the global terrorism database. I wa

2条回答
  •  自闭症患者
    2021-02-01 11:54

    Something like this? This is a solution using rgdal and ggplot. I long ago gave up on using base R for this type of thing.

    library(rgdal)        # for readOGR(...)
    library(RColorBrewer) # for brewer.pal(...)
    library(ggplot2)
    setwd(" < directory with all files >")
    
    gtd        <- read.csv("globalterrorismdb_1213dist.csv")
    gtd.recent <- gtd[gtd$iyear>2009,]
    gtd.recent <- aggregate(nkill~country_txt,gtd.recent,sum)
    world      <- readOGR(dsn=".",
                          layer="world_country_admin_boundary_shapefile_with_fips_codes")
    
    countries <- world@data
    countries <- cbind(id=rownames(countries),countries)
    countries <- merge(countries,gtd.recent, 
                       by.x="CNTRY_NAME", by.y="country_txt", all.x=T)
    map.df <- fortify(world)
    map.df <- merge(map.df,countries, by="id")
    ggplot(map.df, aes(x=long,y=lat,group=group)) +
      geom_polygon(aes(fill=nkill))+
      geom_path(colour="grey50")+
      scale_fill_gradientn(name="Deaths",
                           colours=rev(brewer.pal(9,"Spectral")),
                           na.value="white")+
      coord_fixed()+labs(x="",y="")
    

    There are several versions of the Global Terrorism Database. I used the full dataset available here, and then subsetted for year > 2009. So this map shows total deaths due to terrorism, by country, from 2010-01-01 to 2013-01-01 (the last data available from this source). The files are available as MS Excel download, which I converted to csv for import into R.

    The world map is available as a shapefile from the GeoCommons website.

    The tricky part of making choropleth maps is associating your data with the correct polygons (countries). This is generally a four step process:

    1. Find a field in the shapefile attributes table that maps (no pun intended) to a corresponding field in your data. In this case, it appears that the field "CNTRY_NAME" in the shapefile maps to the field "country_txt" in gtd database.
    2. Create an association between ploygon IDs (stored in the row names of the attribute table), and the CNTRY_NAME field.
    3. Merge the result with your data using CNTRY_NAME and country_txt.
    4. Merge the result of that with the data frame created using the fortify(map) - this associates ploygons with deaths (nkill).

提交回复
热议问题