3

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)
BonnieM
  • 191
  • 1
  • 13

1 Answers1

4

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))

stefan
  • 90,330
  • 6
  • 25
  • 51
  • This works to make the map you shared, and mostly accomplishes what I'm looking for. However, it does not work if you project the map along curved lines (like the ```"laea"``` projection I used in my example code). To the trained eye, this projection is not the best. Perhaps for ```geom_rect``` to work the lines need to be straight. – BonnieM Sep 07 '21 at 23:42
  • 1
    Hm. I see. I'm afraid I lack the geospatial knowledge to get this done without doing a some research for which I lack the time. I can only imagine that we have to transform the coordinates for the bars and to get straight bars we probably have to use geom_polygon. – stefan Sep 08 '21 at 09:58
  • I'm going to mark this as the answer anyway. – BonnieM Sep 08 '21 at 13:32