1

I see some people using R to fill maps from shapefiles, e.g. here. With my R knowledge, I only read the shapefile and plot it.

With QGIS I added an extra column to the attribute table called "OCCURENCE". This column is a year when a specific event occurred. I'd like to fill each country according to the year of occurence using a color scale, leaving the countries with no data without fill. The folder with the shapefiles is here. As example, I added some years to a few countries, and I like to obtain something like:

enter image description here and a legend enter image description here.

library(rgdal)
library(ggplot2)

World <- readOGR(dsn = "mundo", layer = "mundo")
class(World)

World2 <- fortify(World)
class(World2)

ggplot() + 
  geom_polygon(data = World2, aes(x = long, y = lat, group = group),
               colour = "black", size = 0.5, fill = "white")

enter image description here

Any help??

Daniel Valencia C.
  • 2,159
  • 2
  • 19
  • 38
  • 1
    What choropleth answers on SO were unhelpful so we know what research you did for this heavily asked question and can then not spin cycles suggesting things you already knew/did. – hrbrmstr Dec 06 '17 at 03:13
  • 1
    In a simple way, you can use the `sf` package. `mydata <- st_read(dsn = ".", layer = "mundo"); ggplot() + geom_sf(data = mydata, aes(fill = OCCURENCE))` – jazzurro Dec 06 '17 at 03:22

1 Answers1

3

The simple way, as @jazzurro said, is to work with sf package. But, you can achieve this with the method proposed by you adding a couple of steps.

You need to add an id field in SpatialPolygonsDataFrame and join these attributes with fortify() product. With this, you can fill polygons with any field:

library(rgdal)
library(ggplot2)

World <- readOGR(dsn = "mundo", layer = "mundo")
class(World)

World2 <- fortify(World)
class(World2)

World@data$id <- 0:(dim(World@data)[1]-1) # add id field

World2_join = plyr::join(x = World2,y = World@data, by="id") # join by id

ggplot() + 
  geom_polygon(data = World2_join, aes(x = long, y = lat, group = group, fill = OCCURENCE), # fill by OCCURENCE
               colour = "black", size = 0.5)

enter image description here

aldo_tapia
  • 1,153
  • 16
  • 27