I would like to add bar charts to a map in ggplot2. Similar questions exist (this one and this one) but their answers involve ggsubplot, which is deprecated.
geom_scatterpie()
provides a way to do this with pie charts (example 1 but also see example 2), but pie charts are not as visually intuitive as bar charts. Similarly, we can plot bubble size onto a map using geom_sf(size=)
as explained here. So is there a way to do this with bars instead?
Reproducible example for making one bar per location:
# devtools::install_github("hrbrmstr/albersusa")
library(albersusa)
library(sf)
library(ggplot2)
# make a map
statesus <- fortify(usa_sf("laea"))
p <- ggplot() +
geom_sf(data=statesus, size=0.4)
# set up the data
lat <- c(-68.24, -109.88, -80.88, -113.85)
lon <- c(44.35, 38.24, 25.37, 48.75)
park <- c("Acadia", "Canyonlands", "Everglades", "Glacier")
proportion <- c(0.10, 0.80, 0.05, 0.45) # bar heights
parkdat <- data.frame(lat=lat, lon=lon, park=park, proportion=proportion)
parkdatsf <- st_as_sf(parkdat,
coords=c(lon="lon", lat="lat"),
crs=4326,
agr="constant")
# add points to the map (ideally these would be bars)
p + geom_sf(data=parksdatsf)
Adding bars as points sounds a bit awkward to me. If you want to add bars to your map one option would be to make use of geom_rect
like so:
library(sf)
library(ggplot2)
library(albersusa)
p <- ggplot() +
geom_sf(data=usa_sf(), size=0.4) +
theme_minimal()
scale <- 10
width <- 4
p +
geom_rect(data=parkdat, aes(xmin = lat - width / 2, xmax = lat + width / 2, ymin = lon, ymax = lon + proportion * scale, fill = park))