I'm adding bar-plots to maps using ggplot and ggsubplot, but cannot figure out how to specify which to plot first. I'd like to plot the northerly ones first so they sit behind any overlapping plots. With a low fill alpha these should still be viewable. This is the workflow:
library(ggsubplot)
library(ggplot2)
library(maps)
library(plyr)
world_map = map_data("world")
(p = ggplot() + geom_polygon(data = world_map, aes(x=long, y=lat,group=group)))
d = ddply(world_map,.(region),summarize,long=mean(long),lat=mean(lat))
d = d[sample(1:nrow(d), 50),]
d = rbind(d,d)
d$cat = rep(c('A','B'), each=nrow(d)/2)
d$value = sample(1:10, nrow(d), rep=T)
head(d)
p + geom_subplot(data=d, aes(long, lat, group=region, subplot = geom_bar(aes(cat, value, fill=cat),
col='black', alpha=0.9, stat="identity")), width = 30, height=30)
As you can see the plot order seems pretty random. So I tried to change region (country) to an ordered factor:
d$region = factor(d$region, ordered=T)
(ord = count(d[,c('region','lat')], vars=c('region','lat')))
ordered_levels = order(ord$lat, decreasing=T)
print(ord[ordered_levels,])
levels(d$region) = levels(d$region)[ordered_levels]
levels(d$region)
p + geom_subplot(data=d, aes(long, lat, group=region, subplot = geom_bar(aes(cat, value, fill=cat),
col='black', alpha=0.9, stat="identity")), width = 30, height=30)
But this does not seem to solve the problem. Very grateful for any suggestions.