All examples By author By category About

timelyportfolio

Using Concaveman in R using V8 with beeswarm (fork)

Just for fun, I thought I would fork Ramnath Vaidyanathan's concaveman in R example and extend to use with the beeswarm package. I don't think there is any good use case for it, but perhaps somebody might like.

concaveman <- function(d){
  library(V8)
  ctx <- v8()
  ctx$source('https://www.mapbox.com/bites/00222/concaveman-bundle.js')
  jscode <- sprintf(
    "var points = %s;var polygon = concaveman(points);", 
    jsonlite::toJSON(d, dataframe = 'values')
  )
  ctx$eval(jscode)
  setNames(as.data.frame(ctx$get('polygon')), names(d))
}

library(beeswarm)
library(ggplot2)
library(dplyr)

# example from beeswarm
data(breast)
# play with method - square, hex, center
bsw = beeswarm(time_survival ~ ER, data = breast, method="square")

# transfrom with dplyr
bsw_cvman <- bsw %>%
  data.frame(row.names = NULL) %>%
  group_by(x.orig) %>%
  summarise(
    cvman = list(concaveman(data.frame(x,y)))
  )

Reduce(
  function(left, right) {
    left + 
      geom_path(data=right, aes(x,y))
  },
  bsw_cvman$cvman,
  init = ggplot(bsw, aes(x = x, y = y)) +
    scale_x_discrete(limits = unique(bsw$x.orig))
)