Last active
August 10, 2016 21:58
-
-
Save dantonnoriega/6e6e024ce71acb3c6797f1dd8104832d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# highcharter example: creating "scatter columns" with medians | |
# goal: scatter plot mpg by cyl, highlight medians | |
library(highcharter) | |
library(dplyr) | |
library(tibble) | |
library(purrr) | |
# BUILD HC DATA ------------------------------------------------ | |
# convert to tibble | |
df_hc <- mtcars %>% | |
rownames_to_column(var = 'car') %>% | |
as_data_frame %>% | |
mutate(cyl = as.character(cyl)) # make it categorical | |
# make marker options for median points | |
mrkr_opts <- list(lineColor = "#000000", | |
lineWidth = 2, | |
radius = 7, | |
states = list( | |
hover = list( | |
enabled = FALSE | |
) | |
) | |
) | |
# split data by cyl | |
medians <- df_hc %>% | |
group_by(cyl) %>% | |
summarize(y = median(mpg)) %>% | |
rename(name = cyl) %>% | |
split(.$name) | |
# convert to list of data_frames to lists of HC point data | |
## NOTE: name convention is explicit i.e. "y", "name", "marker" follow highcharts API | |
## "car" DOES NOT follow the api but this data is call in the tooltip formatter | |
data_p50 <- medians %>% | |
map(as.list) %>% # convert to list (required ) | |
map(append, | |
list(marker = mrkr_opts, car = 'Median')) %>% # add marker data | |
setNames(NULL) | |
data_p50 # each element of data_p50 is a point with marker characteristics | |
# PLOT ------------------------------------------------ | |
# create tooltip hover that shows the car name (or median) then mpg | |
fmt <- JS("function() { | |
return this.point.car + ': <b>' + | |
this.point.y + '</b> mpg' | |
}") | |
hc <- hchart(df_hc, x = cyl, y = mpg, type = 'scatter') %>% | |
hc_xAxis(categories = c("4", "6", "8")) %>% # reorder categories | |
hc_add_series(data = data_p50, type = 'scatter') %>% | |
hc_tooltip(formatter = fmt) | |
hc | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment