Capturing Screenshots of HTML Output in R Code
First, we will create the HTML widget, then save it as an HTML file and then take a screenshot using the webshop package.
R
library (htmlwidgets) library (dygraphs) library (webshot) # Create the dygraph widget widget <- dygraph (LakeHuron) %>% dyAxis ( "x" , label = "Time" ) %>% dyAxis ( "y" , label = "Level of Lake Huron" ) # Save the dygraph widget as an HTML file saveWidget (widget, file = "widget.html" , selfcontained = TRUE ) # Save the screenshot of widget webshot (url = "./widget.html" , file = "./screenshot_widget.jpg" ) |
Output:
Here we have used the dygraphs package of R. It is used for plotting time-series data i.e. dataset which shows variations with time. There are a couple of preloaded datasets in R to try this out like the EuStockMarkets, austres, JohnsonJohnson, and LakeHuron. Here we will use the LakeHuron dataset which contains data about the levels of Lake Huron from 1875 till 1972.
We simply pass the dataset to the dygraph() function of dygraphs package in order to plot it and for clarity, we have labeled the x-axis as “Time” and the y-axis as “Level of Lake Huron”. The plot generated in the HTML file widget.html is an interactive one. Finally after the a creation of html file the webshot() function takes a screenshot of the widget in the html file as mentioned in url parameter and saves it in the file parameter value.
How to Embed htmlwidgets into Documents in R
HTML widgets in R Programming Launagauge are interactive web components, JavaScript-based visualizations that can be easily integrated into different documents. They are built on top of the HTML widgets package, which provides a framework for creating R bindings to JavaScript libraries. Examples of HTML widgets available for R include leaflet, dygraphs, Plotly, DiagrammeR, and others.
HTML widgets can be embedded directly into various types of documents created in R, such as R Markdown files, Shiny web applications, and standalone HTML pages, and even indirectly into documents like Word, Excel, PowerPoint, and PDF files. Embedding HTML widgets into documents ensures reproducibility, eliminating any discrepancies that may arise from the manual re-creation of the same document on different setups and environments.
Prerequisites :-
The various implementations in different documents have been described below.
Contact Us