mccandar
mccandar

Reputation: 788

R highcharter get data from plots saved as html

I plot data with highcharter package in R, and save them as html to keep interactive features. In most cases I plot more than one graph, therefore bring them together as a canvas.

require(highcharter)
hc_list <- lapply(list(sin,cos,tan,tanh),mapply,seq(1,5,by = 0.1)) %>% 
  lapply(function(x) highchart() %>% hc_add_series(x))
hc_grid <- hw_grid(hc_list,ncol = 2)

htmltools::browsable(hc_grid) # print
htmltools::save_html(hc_grid,"test_grid.html") # save

enter image description here

I want to extract the data from plots that I have saved as html in the past, just like these. Normally I would do hc_list[[1]]$x$hc_opts$series, but when I import html into R and try to do the same, I get an error. It won't do the job.

> hc_imported <- htmltools::includeHTML("test_grid.html")
> hc_imported[[1]]$x$hc_opts$series
Error in hc_imported$x : $ operator is invalid for atomic vectors

If I would be able to write a function like

get_my_data(my_imported_highcharter,3) # get data from 3rd plot

it would be the best. Regards.

Upvotes: 1

Views: 1306

Answers (1)

Rolando Tamayo
Rolando Tamayo

Reputation: 286

You can use below code

require(highcharter)
hc_list <- lapply(list(sin,cos,tan,tanh),mapply,seq(1,5,by = 0.1)) %>% 
  lapply(function(x) highchart() %>% hc_add_series(x))
hc_grid <- hw_grid(hc_list,ncol = 2)

htmltools::browsable(hc_grid) # print
htmltools::save_html(hc_grid,"test_grid.html") # save

# hc_imported <- htmltools::includeHTML("test_grid.html")
# hc_imported[[1]]$x$hc_opts$series

library(jsonlite)
library(RCurl)
library(XML)

get_my_data<-function(my_imported_highcharter,n){
  webpage <- readLines(my_imported_highcharter)
  pagetree <- htmlTreeParse(webpage, error=function(...){})

  body <- pagetree$children$html$children$body 

  divbodyContent <- body$children$div$children[[n]]

  script<-divbodyContent$children[[2]]

  data<-as.character(script$children[[1]])[6]

  data<-fromJSON(data,simplifyVector = FALSE)

  data<-data$x$hc_opts$series[[1]]$data

  return(data)
}     

get_my_data("test_grid.html",3)


get_my_data("test_grid.html",1)

Upvotes: 3

Related Questions