Reputation: 21
I've been trying to teach myself R and have run into a problem. Apologies if it is a silly question but I can't seem to find an answer to it in other topics.
I'm trying to plot a world map. I can plot a world map with color varying by country. My code is:
library("maptools")
library("tidyverse")
data("wrld_simpl")
new_wrld <- fortify(wrld_simpl, region = "NAME")
#new_tab<-data.frame(wrld_simpl$NAME,as.character(wrld_simpl$REGION))
#colnames(new_tab)<-c("id","region_num")
#str(new_wrld)
#new_wrld<-merge(new_wrld,new_tab, by.x = "id", by.y = "id")
#new_wrld$region_num<-as.character(new_wrld$region_num)
#str(new_wrld)
gg<- ggplot(data = new_wrld, aes(x = long, y = lat, map_id = id, fill = id))+ geom_map(map = new_wrld, color = "Black")
gg<- gg + theme(panel.background = element_rect(fill = "lightblue"),
panel.grid = element_blank(),
legend.position = "None")
gg<- gg + xlim(-180,180) + ylim(-90,90)
gg
As you may be able to guess, in the commented out lines I'm trying to extract the region (read: continent) and merge this into my dataframe so that I can colour the map by continent rather than by country. From the output of the two calls to str() as far as I can see I am achieving this: the only difference is the addition of an eighth variable, new_wrld$region_num. But as soon as I uncomment that chunk and run the code I get the error:
Error in unit(x, default.units) : 'x' and 'units' must have length > 0
And I don't know why. My plan was then to change the "fill = id" in the ggplot() call to "fill = region_num" to produce a map with each continent shaded a different colour.
Any help would be much appreciated.
Upvotes: 2
Views: 2780
Reputation: 29125
You can save the merged dataset separately, & use that to define the fill palette while keeping the original fortified dataset for the map:
new_wrld2 <- merge(new_wrld,new_tab, by.x = "id", by.y = "id")
ggplot(data = new_wrld2,
aes(x = long, y = lat, map_id = id, fill = region_num)) +
geom_map(map = new_wrld, color = "Black") +
theme(panel.background = element_rect(fill = "lightblue"),
panel.grid = element_blank(),
legend.position = "None") +
xlim(-180,180) + ylim(-90,90)
Upvotes: 1