block by timelyportfolio 1cce2d1190460a7f1406945bdc02f4e1

Plotly and statebins [R]

Full Screen

Statebins in Plotly

Introduction

Bob Rudis @hrbrmstr gave us the statebins package. Since we are in the middle of election season, I wanted to see how we could combine the convenience of statebins with interactivity from plotly. Thanks to @cpsievert for improving my first ugly version.

Install and Load Packages

#devtools::install_github("ropensci/plotly")
#install.packages("statebins")
library(plotly)
library(statebins)

Statebins | ggplot2

The statebins set of functions generates a ggplot2 plot. Let’s look at a simple example.

(sb <- statebins(
  data.frame(
    state = rownames(state.x77),
    state.x77,
    stringsAsFactors = FALSE
  ),
  value_col = "Illiteracy"
))

Statebins | ggplotly

Since statebins are ggplot, let’s see if we can just use the very handy ggplotly tranform function from plotly. Close but not quite there.

ggplotly(sb)

Statebins | plotly

I think the convenience of ggplotly often dissuades from learning the very powerful core plotly system.

library(plotly)
library(dplyr)

# get statebin data
d <- data.frame(
  state = rownames(state.x77),
  state.x77,
  stringsAsFactors = FALSE
) 
d <- inner_join(d, statebins:::state_coords)

# create variable with hovertext displaying values of every variable
vars <- Map(
  function(x, y) paste0(x, ": ", y),
  names(d)[1:(ncol(d)-4)],
  d[,1:(ncol(d)-4)]
)
d$txt <- Reduce(function(x, y) paste0(x, "<br />", y), vars)

# an "empty" plotlyjs axis for layout
emptyAxis <- list(
  title = "", 
  zeroline = FALSE,
  showline = FALSE, 
  showticklabels = FALSE, 
  showgrid = FALSE
)

plot_ly(d, x = ~col, y = ~-row) %>%
  add_markers(
    color = ~Illiteracy,
    text = ~txt,
    symbol = I("square"), #lots of options here
    size = I(200),
    hoverinfo = "text"
  ) %>%
  add_text(text = ~abbrev, color = I("white"), hoverinfo = "none") %>%
  layout(showlegend = FALSE, xaxis = emptyAxis, yaxis = emptyAxis)

For some inspiration, try the lasso select and think about how we might use that to communicate.

Statebins | plotly symbols

At the risk of taking this too far, I wanted to highlight all the symbols (see the full list) that we have available with Plotly.

plot_ly( d, x = ~col, y = ~-row) %>%
  add_trace(
    color = ~Illiteracy,
    text = ~txt,
    marker = list(
      symbol =  ~ifelse(col>6,I("triangle-nw"),I("star-square"))
    ),
    size = I(350),
    hoverinfo = "text",
    mode = "markers",
    type = "scatter"
  ) %>%
  add_text(text = ~abbrev, color = I("white"), hoverinfo = "none") %>%
  layout(showlegend = FALSE, xaxis = emptyAxis, yaxis = emptyAxis)