block by timelyportfolio 3793462de638478937ac

stateface from propublica used in R ggplot

Full Screen

The R world is hot with ideas from @hrbrmstr and @ramnathv using icons, isotypes, waffles, and statebins. As I examined their work with awe, I remembered the stateface font library from @propublica. I started trying to work through ways to combine it all.

in rcstatebin

For stateface in statebin, see this issue.

in ggplot2

Below is the code to use stateface in ggplot2 with the built-in state data in R. You can see the live result here. I just used gridSVG to export the ggplot2 so that it will show up in the web page.

library(extrafont)

### using forked version of rcstatebin
#devtools::install_github("timelyportfolio/rcstatebin@feature/stateface")

### import stateface font from propublica
###   https://github.com/propublica/stateface
font_import(
  system.file("htmlwidgets/lib/stateface/font/webfont",package="rcstatebin")
  ,pattern="stateface-regular-webfont.ttf"
)
choose_font("StateFace")

### make lookup table for the stateface font to state abbreviation
state_labels <- structure(
  c(
    "A", "B", "C", "D", "E", "F", "G", "y"
    , "H", "I",  "J", "K", "L", "M", "N", "O"
    , "P", "Q", "R", "S", "T", "U", "V",  "W"
    , "X", "Y", "Z", "a", "b", "c", "d", "e"
    , "f", "g", "h", "i",  "j", "k", "l", "3"
    , "m", "n", "o", "p", "q", "z", "r", "s"
    , "t",  "u", "v", "w", "x"
  )
  , .Names = c(
    "AK", "AL", "AR", "AZ", "CA",  "CO"
    , "CT", "DC", "DE", "FL", "GA", "HI"
    , "IA", "ID", "IL", "IN",  "KS", "KY"
    , "LA", "MA", "MD", "ME", "MI", "MN"
    , "MO", "MS", "MT",  "NC", "ND", "NE"
    , "NH", "NJ", "NM", "NV", "NY", "OH"
    , "OK", "OR",  "PA", "PR", "RI", "SC"
    , "SD", "TN", "TX", "US", "UT", "VA"
    , "VT",  "WA", "WI", "WV", "WY")
  )
### use V8 as an example for step above
#library(V8)
#ct <- new_context()
#ct$source(system.file("htmlwidgets/lib/stateface/stateface.js",package="rcstatebin"))
#state_labels <- unlist(ct$get("stateface.lookup"))
#state_labels <- state_labels[order(names(state_labels))]

library(ggplot2)

ggplot(
  data.frame(
    abb = state.abb
    , state.x77[,c("Population","Area")]
    , region = state.region
  )
  , aes(x = Population, y=Area)
) +
  geom_text(
    aes(
      label=state_labels[-(which(!(names(state_labels) %in% state.abb))) ][state.abb]
      #,size=area
    )
    , family="StateFace", alpha = 0.5, size = 6, hjust = 0
  ) +
  geom_text( aes( label = abb ), size = 4, hjust = 1 ) +
  geom_hline( x = 0 ) +
  facet_wrap( ~region ) +
  theme_minimal()