Search code examples
rggplot2choropleth

How to add count labels to statebin map?


The following code creates a statbin heatmap. How can we add labels with the counts to each bin? (Desired labels have been prepared in the lab column of the data.)

library(statebins)

dat = data.frame(state = state.abb, val = rep(0:24, 2))
dat$lab = paste(dat$state, dat$val, sep = "\n")
head(dat)
#   state val   lab
# 1    AL   0 AL\n0
# 2    AK   1 AK\n1
# 3    AZ   2 AZ\n2
# 4    AR   3 AR\n3
# 5    CA   4 CA\n4
# 6    CO   5 CO\n5

sb = statebins(dat, state_col = "state", value_col = "val") +
  theme_statebins()
sb

enter image description here


Solution

  • We can edit the geom_text label in the built plot directly like this, making sure to match the labels in the correct order:

    library(ggplot2)
    
    sb = ggplot_build(sb)
    sb$data[[2]]$label = dat$lab[match(sb$data[[2]]$label, dat$state)]
    sb = ggplot_gtable(sb)
    plot(sb)
    

    enter image description here