Skip to content

Instantly share code, notes, and snippets.

@johnmarquess
Last active October 13, 2016 23:37
Show Gist options
  • Save johnmarquess/153ea4b0672e9d1479bc6b0ee3f2e138 to your computer and use it in GitHub Desktop.
Save johnmarquess/153ea4b0672e9d1479bc6b0ee3f2e138 to your computer and use it in GitHub Desktop.
A map with a smaller inset map
library(maptools)
library(ggplot2)
library(rgdal)
library(ggthemes)
library(rgeos)
library(Cairo)
library(ggmap)
library(scales)
library(RColorBrewer)
library(dplyr)
library(grid)
library(raster)
qld <- readShapeSpatial('qld_shp/HHS_QLD_region-2014.shp')
qld <- gBuffer(qld, byid = TRUE, width=0)
num_hhs <- length(qld$HHS)
qld_data <- data.frame(id=qld$HHS, prev=rnorm(num_hhs, 40, 25))
qld_f <- fortify(qld, region='HHS')
merged_df <- merge(qld_f, qld_data, by='id', all.x=TRUE)
qld_final <- merged_df[order(merged_df$order), ]
cnames <- aggregate(cbind(long, lat) ~ id, data=qld_final, FUN=function(x) mean(range(x)))
inset_hhs <- c('Metro North', 'Metro South', 'Gold Coast', 'Sunshine Coast', 'West Moreton')
qld_inset <- qld_final %>% filter(id %in% inset_hhs)
inset_names <- aggregate(cbind(long, lat) ~ id, data=qld_inset, FUN=function(x) mean(range(x)))
inset_rect <- data.frame(xmin=151.6,xmax=153.8 ,ymin=-28.5 ,ymax=-25.6)
# MAIN MAP
p1 <- ggplot() + geom_polygon(data=qld_final, aes(x =long, y=lat, group=group, fill=prev), color='grey45') +
scale_fill_gradient(name="Percent", limits=c(0,100), low="white", high="red") +
coord_map()+
geom_text(data=cnames, aes(long, lat, label = id), size=2.5, fontface="bold") +
theme_nothing(legend=TRUE) +
theme(plot.title = element_text(size=16, face="bold",hjust=0, vjust = 0.2)) +
ggtitle("Incidence of random numbers between 1 and 100 in Queensland\nduring the period 2005 to 2010")
# INSET
p2 <- ggplot() + geom_polygon(data=qld_final, aes(x =long, y=lat, group=group, fill=prev), color='grey45') +
scale_fill_gradient(name="Percent", limits=c(0,100), low="white", high="red") +
coord_map() +
coord_cartesian(xlim = c(151.6,153.8), ylim = c(-28.5, -25.6), expand = FALSE) +
theme_nothing() +
geom_text(data=inset_names, aes(long, lat, label = id), size=2.5, fontface="bold") +
geom_rect(data = inset_rect, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), alpha=0, colour="grey45", size = 1, linetype=1)
png(filename = 'test.png',width = 8, height = 8, res = 640, units = 'in')
grid.newpage()
v1<-viewport() #plot area for the main map
v2<-viewport(width = 0.275, height = 0.35, x = 0.65, y = 0.75) #plot area for the inset map
print(p1,vp=v1)
print(p2,vp=v2)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment