I am having trouble creating a map with growing and shrinking bubbles with ggplotly. I have never used plotly before, so there might be an obvious solution to this. There's really no need for me to try and describe the problem more than just showing you what the problem is. It is rather obvious. This link gives you the following interactive map.
As you can see, the bubbles are growing and shrinking nicely, but the problem is that every second year, the bubbles appear behind the polygon. This is the only problem, plotting the years separately works fine.
And here's the code, which you should be able to copy and run. Note that I'm using geocodes
from the ggpmap package to download coordinates for every country. There's a limit of 2500 free downloads per day.
library(ggplot2)
library(plotly)
library(wbstats)
library(countrycode)
library(ggmap)
startdate = 2010
enddate = 2016
indicator <- "SM.POP.REFG"
# download data
dat <- wb(indicator = indicator,
startdate = startdate,
enddate = enddate)
# download map data
worlds <- map_data("world")
worlds$iso2c = countrycode(worlds$region,
origin = "country.name",
destination = "iso2c")
# merge map data and wb data
merged <- merge(worlds, subset(dat, date==2016), sort=F, by="iso2c")
merged <- merged[order(merged$order), ]
# download geocodes (might take a minute or two)
cords <- geocode((unique(merged$country)))
cords <- data.frame(unique(merged$iso2c),unique(merged$country),cords)
colnames(cords) <- c("iso2c","country","lon","lat")
#
valuestocords <- unique(dat[,c("value","country","date")])
newdata = merge(cords, valuestocords, by = "country")
# plot
g <- ggplot(merged, aes(long, lat))+
geom_polygon(aes(group = group), fill="grey")+
geom_point(data=newdata, aes(lon, lat, size=value, ids=country, frame=date), alpha=0.5)+
scale_size_area()
ggplotly(g)