I am trying to refine this plot.
- I want to get a customized legend in which the countries associated with the same color are together in the same category (not with the same color box repeated over and over again) Ideally, I would want something like
-5: [red box] list of countries with value -5
-4: [light red box] list of countries with value -4
etc.
- Russia is cut in the upper right corner... How do I expand the limits of this plot to cover it all? Thank you so much! Here's my code:
library(RColorBrewer)
library(maptools)
library(ggplot2)
library(tidyverse)
if (!require(gpclib)) install.packages("gpclib", type="source")
gpclibPermit()
data(wrld_simpl)
ddf <- read.table(text="
country value
'Argentina' 2
'Australia' 3
'Belgium' 5
'Brazil' 17
'Canada' 2
'China' -2
'France' 7
'Germany' 97
'Indonesia' -2
'Italy' 9
'Japan' 9
'Portugal' -2
'Russia' 3
'Saudi Arabia' 2
'Singapore' -5
'Slovenia' 1
'Spain' -3
'Switzerland' 0
'Turkey' 0
'United States' 18", header=TRUE)
ddf$color <- case_when(ddf$value==1 ~ "#66FFFF",
ddf$value==2 ~ "#3399CC",
ddf$value==3 ~ "#0066CC",
ddf$value==4 ~ "#3333FF",
ddf$value>=5 ~ "#000066",
ddf$value==0 ~ "#FFCC66",
ddf$value==-1 ~ "FF9900",
ddf$value==-2 ~ "#FF6600",
ddf$value==-3 ~ "#FF0000",
ddf$value==-4 ~ "#CC0000",
ddf$value<=-5 ~ "#990000")
plotme <- function() {
# this lets us use the contry name vs 3-letter ISO
wrld_simpl@data$id <- wrld_simpl@data$NAME
wrld <- fortify(wrld_simpl, region="id")
wrld <- subset(wrld, id != "Antarctica") # we don't rly need Antarctica
gg <- ggplot()
# setup base map
gg <- gg + geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat), fill="white", color="#7f7f7f", size=0.15)
# add our colored regions
gg <- gg + geom_map(data=ddf, map=wrld, aes(map_id=country, fill=country), color="#7f7f7f", size=0.15)
# this sets the scale and, hence, the legend
gg <- gg + scale_fill_manual(values=ddf$color,
name="Interactions")
# this gives us proper coords. mercator proj is default
gg <- gg + coord_map()
gg <- gg + labs(x="", y="")
gg <- gg + theme(plot.background = element_rect(fill = "transparent", colour = NA),
panel.border = element_blank(),
panel.background = element_rect(fill = "transparent", colour = NA),
panel.grid = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.position = "bottom")
gg
}
plotme()
And here's my plot: