Skip to content

Instantly share code, notes, and snippets.

@harrismcgehee
Created March 10, 2017 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrismcgehee/06d18a69e97bfdaf55ebf43fdb8b3c98 to your computer and use it in GitHub Desktop.
Save harrismcgehee/06d18a69e97bfdaf55ebf43fdb8b3c98 to your computer and use it in GitHub Desktop.
Annotate map with circles
# Prep ----
library(ggplot2)
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
crimesm <- reshape2::melt(crimes, id = 1)
states_map <- map_data("state")
# Make your map ------
map <- ggplot(crimes, aes(map_id = state)) +
geom_map(aes(fill = UrbanPop), map = states_map) +
expand_limits(x = states_map$long, y = states_map$lat) +
coord_map(projection = "polyconic") +
theme_void() +
theme(legend.position = "none")
map
# Make the map a grid graphical object (“grob”) ------
# https://stat.ethz.ch/R-manual/R-devel/library/grid/html/grid.grob.html
grobMap <- ggplotGrob(map)
# Make a container canvas ------
df <- data.frame(x = 1:10, y = 1:10)
container_plot <- ggplot(df, aes(x, y)) +
geom_blank() +
theme_void()
container_plot
# Add a custom annotation. To do that, you pass it a grob ----
container_plot +
annotation_custom(grob = grobMap)
# Then add your circle annotation / custom ribbon annotation ------
#' alternatively ggforce::geom_circle?
#' http://stackoverflow.com/a/39071128/4386615
gg_circle <- function(r, xc, yc, color="black", fill=NA, ...) {
x <- xc + r*cos(seq(0, pi, length.out=100))
ymax <- yc + r*sin(seq(0, pi, length.out=100))
ymin <- yc + r*sin(seq(0, -pi, length.out=100))
annotate("ribbon", x=x, ymin=ymin, ymax=ymax, color=color, fill=fill, ...)
}
# Also remove text and ticks and lines in theme ----
container_plot +
annotation_custom(grob = grobMap) +
gg_circle(r=1, xc=2.5, yc=6, fill="red", alpha=.5) +
geom_text(aes(label="65%"), x=2.5, y=6) +
theme_void()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment