2

I'm using the default world map from rworldmaps as a background layer for a bunch of plots done with ggplot2. In order to do this I have to "fortify" the object returned by getMap() - this converts it to a format ggplot understands.

Given

> library(maptools)
> library(rworldmap)
> library(ggplot2)

and the 'rgeos' package also installed, this works, but gives me a message which makes it sound like I really ought to specify the "region=" argument:

> world <- fortify(getMap())
Regions defined for each Polygons

I want the background layer to show country borders, so I think I ought to specify region="ADMIN", but this fails:

> world <- fortify(getMap(), region="ADMIN")
Error: IllegalArgumentException: Points of LinearRing do not form
a closed linestring

I get the same error message for other plausible region= settings (NAME, ISO_A2, REGION, continent, etc).

What is going on and what is the correct way to do what I want?

2

I wouldn't bother with the region argument, in this case it means your features get unioned together based on the "ADMIN" grouping. With ggplot aesthetics you don't need to do this kind of union, you can just change the colours etc. (Unless you want to show polygon borders and not show the internal ones where polygons are grouped . . .)

rgeos gets invoked here to do the union, and for whatever reason there is a geometric detail that it doesn't like. (Please see the new sf package now on CRAN for the future of these tools in R, it's all different but that's where things are going).

I would just stick with ggplot2 aesthetics to "display the grouping":

library(maptools)
library(rworldmap)
library(ggplot2)

w <- getMap()
## we need to id to join back
w$id_1 <- row.names(w)
world <- fortify(w)

library(dplyr)
world <- world %>% inner_join(as.data.frame(w)[, c("ADMIN", "id_1")], c("id" = "id_1"))

ggplot(world) + aes(x = long, y = lat, group = group, fill = ADMIN) + geom_polygon() + guides(fill = FALSE)

In this case ADMIN and row.names are the same, so it's a bit pointless to join, but the general case would work as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.