Skip to content

Instantly share code, notes, and snippets.

@dantonnoriega
Last active October 25, 2022 12:56
Show Gist options
  • Save dantonnoriega/0744e7537076128ac4a026b8b7f38f09 to your computer and use it in GitHub Desktop.
Save dantonnoriega/0744e7537076128ac4a026b8b7f38f09 to your computer and use it in GitHub Desktop.
htmlwidget-webshot-example.R
# Creating html plots with highcharter and generating high resolution PNGs of plots with webshot
library(highcharter)
# set up directories
OUTPUT_HTML <- '~/Downloads/hc-webshot-example/html'
OUTPUT_PNG <- '~/Downloads/hc-webshot-example/png'
if(!dir.exists(OUTPUT_HTML)) dir.create(OUTPUT_HTML, recursive = TRUE)
if(!dir.exists(OUTPUT_PNG)) dir.create(OUTPUT_PNG, recursive = TRUE)
FILE <- 'drivers_killed'
DF <- Seatbelts %>%
tibble::as_tibble() %>%
tibble::rownames_to_column('ym') %>%
dplyr::mutate(ym = time(Seatbelts) %>% zoo::as.yearmon())
# output an html version on what your plot
html <- file.path(OUTPUT_HTML, paste0(FILE, ".html"))
message(sprintf("Exporting... %s", html))
hc <- hchart(DF, "line", hcaes(x = ym, y = DriversKilled)) %>%
hc_title(text = paste("Drivers Killed")) %>%
hc_yAxis(title = list(text = "Drivers Killed"), min = 0) %>%
hc_plotOptions(series = list(animation = FALSE)) # turn off animation so plots render quickly
htmlwidgets::saveWidget(hc, file = html, libdir = 'html_support_files') # save html widget
# make pngs
htmls <- list.files(OUTPUT_HTML, pattern = "html$", full.names = TRUE) # find list of all html files
pngs <- lapply(htmls, function(j) { # search folder for html widgets, convert to png
dir <- normalizePath(OUTPUT_PNG)
out <- file.path(dir, gsub("html", "png", basename(j))) # copy names, remove html, add png
# user webshot to generate pngs
message(sprintf("Generating... %s", out))
webshot::webshot(j, file = out, delay = 0, vwidth = 1500, vheight=500, zoom=2)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment