An htmlwidget works just like an R plot except it produces an interactive web visualization. A line or two of R code is all it takes to produce a D3 graphic or Leaflet map. Widgets can be used at the R console as well as embedded in R Markdown reports and Shiny web applications. Here’s an example of using leaflet directly from the R console:
When printed at the console the leaflet widget displays in the RStudio Viewer pane. All of the tools typically available for plots are also available for widgets, including history, zooming, and export to file/clipboard (note that when not running within RStudio widgets will display in an external web browser).
Here’s the same widget in an R Markdown report. Widgets automatically print as HTML within R Markdown documents and even respect the default knitr figure width and height.
Widgets also provide Shiny output bindings so can be easily used within web applications. Here’s the same widget in a Shiny application:
The htmlwidgets framework is a collaboration between Ramnath Vaidyanathan (rCharts), Kenton Russell (Timely Portfolio), and RStudio. We’ve all spent countless hours creating bindings between R and the web and were motivated to create a framework that made this as easy as possible for all R developers.
Here are a few widget libraries that have been built so far:
leaflet, a library for creating dynamic maps that support panning and zooming, with various annotations like markers, polygons, and popups.
dygraphs, which provides rich facilities for charting time-series data and includes support for many interactive features including series/point highlighting, zooming, and panning.
networkD3, a library for creating D3 network graphs including force directed networks, Sankey diagrams, and Reingold-Tilford tree networks.
DataTables, which displays R matrices or data frames as interactive HTML tables that support filtering, pagination, and sorting.
rthreejs, which features 3D scatterplots and globes based on WebGL.
All of these libraries combine visualization with direct interactivity, enabling users to explore data dynamically. For example, time-series visualizations created with dygraphs allow dynamic panning and zooming:
To learn more about the framework and see a showcase of the available widgets in action check out the htmlwidgets web site. To learn more about building your own widgets, install the htmlwidgets package from CRAN and check out the developer documentation.
In this series, we walk through lesser-known tips and tricks to help you work more effectively and efficiently in R Markdown. This third post focuses on features that save you time and trouble.
The RStudio IDE includes a visual markdown editor that displays changes in real-time and provides support for technical writing. This post walks through several features of visual editing mode.