简体   繁体   English

R highcharter从另存为html的图中获取数据

[英]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. 我在R中使用highcharter软件包绘制数据,并将其另存为html,以保持交互功能。 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

在此处输入图片说明

I want to extract the data from plots that I have saved as html in the past, just like these. 我想从过去保存为html的图中提取数据,就像这些一样。 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. 通常,我会执行hc_list [[ 1 ]] $ x $ hc_opts $ series,但是当我将html导入R并尝试执行相同操作时,会出现错误。 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. 问候。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM