The next way is to embed interactive chart types into R Markdown documents by using various R packages that enable us to create interactive charts. Some of these package, we have already been introduced to in Chapter 3, R Lesson I – Graphics System. They are as follows:
ggvis
rCharts
googleVis
dygraphs
Therefore, we will not introduce them again, but will introduce some more packages that enable us to build interactive charts. They are:
threejs
networkD3
metricsgraphics
plotly
Please keep in mind that the interactivity logically only works with the HTML output of R Markdown.
We already know the ggvis
package from Chapter 3, R Lesson I: Graphics System. Broadly speaking, ggvis
is the successor to the well-known graphic package, ggplot2
. The interactivity options of ggvis
, which are based on the reactive programming model of the Shiny framework, are also useful for creating interactive R Markdown documents.
If you want to include an interactive ggvis
plot within a normal R Markdown file, make sure to include the runtime: shiny
argument in the YAML header. To create an interactive R markdown document with ggvis
, you need to click on the new file, then on R Markdown..., choose Shiny in the left menu of the new window, and finally, click on OK to create the document. As told before, since ggvis
uses the reactive model of Shiny, we need to create an R Markdown document with ggvis
this way.
As shown, readers of this R Markdown document can easily adjust the bandwidth, and also, the kernel model. The interactive controls are created with input_
. In our example, we used the controls, input_slider()
and input_select()
. For example, some of the other controls are input_checkbox()
, input_numeric()
, and so on. These controls have different arguments depending on the type of input. For both controls in our example, we used the label
argument, which is just a text label shown next to the controls. Other arguments are ID
(a unique identifier for the assigned control) and map
(a function that remaps the output).
Since the rCharts
package creates JavaScript visualizations, the corresponding R code just needs to be embedded in the normal code chunks. The following code produces an interactive line chart:
--- title: "My Interactive Report" author: "Your Name" output: html_document --- ## Interactive documents with rCharts ```{r} library(rCharts) ``` ```{r results = 'asis', message=FALSE} # interactive line chart with MorrisJS # this code example was taken from http://ramnathv.github.io/rCharts/ data(economics, package = 'ggplot2') econ <- transform(economics, date = as.character(date)) m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line', data = econ) m1$set(pointSize = 0, lineWidth = 1) m1$print('chart2', include_assets = TRUE) ...
It is important to include the argument, results = 'asis'
, in the plot rendering chunk. Furthermore, you need to add the argument, include_assets = TRUE
, to the printing function:
The googleVis
package uses the Google Charts API, and therefore, its charts can also be easily executed within the code chunks. The following code produces an interactive bar and line chart combination:
--- title: "My Interactive Report" author: "Your Name" output: html_document --- ## Using googleVis {r, message=FALSE} library(googleVis) op <- options(gvis.plot.tag="chart") ... {r results = 'asis', message=FALSE} # interactive line line and bar with googleVis # this code example was taken from the googleVis package vignette CityPopularity$Mean=mean(CityPopularity$Popularity) CC <- gvisComboChart(CityPopularity, xvar='City', yvar=c('Mean', 'Popularity'), options=list(seriesType='bars', width=450, height=300, title='City Popularity', series='{0: {type:\"line\"}}')) plot(CC) ...
Again, it is important to include the argument, results = 'asis'
, in the chunk that creates the chart.
We already introduced the htmlwidgets
package that enables R users to create interactive web visualizations. Of course, you can also embed HTMNL
widgets in R Markdown documents to make them interactive.
As already known from rCharts
and googleVis
, the dygraphs
package, which was created directly by RStudio, only works with the HTML output of R Markdown.
The following code produces an interactive dygraph
with a range selector:
--- title: "My Interactive Report" author: "Your Name" output: html_document --- ## Using htmlwidgets & dygraphs {r, message=FALSE} library(htmlwidgets) library(dygraphs) ```{r, fig.width=6, fig.height=2.5} # example was taken from http://rstudio.github.io/dygraphs/r-markdown.html dygraph(nhtemp, main = "New Haven Temperatures") %>% dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01")) ...
The threejs package defines an interactive 3-d scatterplot and globe plot using three.js and the htmlwidgets package for R. These examples render like normal R plots in RStudio. They also work in R Markdown documents, shiny, and from the R command line. | ||
--B.W. Lewis (http://bwlewis.github.io/rthreejs/) |
Since threejs
is not on CRAN and must be installed via GitHub in the usual manner, we use the following code snippet:
library(devtools) install_github("bwlewis/rthreejs") library(threejs)
The following code example produces an interactive 3D scatterplot, on which axes can virtually move freely back and forth:
--- title: "My Interactive Report" author: "Your Name" output: html_document --- ## Using htmlwidgets & threejs {r, message=FALSE} library(htmlwidgets) library(threejs) {r} # example was taken from http://bwlewis.github.io/rthreejs/ N <- 100 i <- sample(3, N, replace=TRUE) x <- matrix(rnorm(N*3),ncol=3) lab <- c("small", "bigger", "biggest") scatterplot3js(x, color=rainbow(N), labels=lab[i], size=i, renderer="canvas")
The networkD3
package is based on the d3Network
package and also uses the capabilities of the htmlwidgets
package to create D3 JavaScript network graphs with R. The package can be downloaded from CRAN and was created by Cristopher Gandrud and JJ Allaire. The networkD3
package supports different types of interactive network graphs. In the following example, we use the forceNetwork
graph type. Interactivity is given by the options to hover over all the nodes and read the inputs, and further, you can move the whole network back and forth:
--- title: "My Interactive Report" author: "Your Name" output: html_document --- ## Using htmlwidgets & networkD3 ```{r} library(htmlwidgets) library(networkD3) ``` ## forceNetwork ```{r} # example was taken from http://christophergandrud.github.io/networkD3/#force data(MisLinks) data(MisNodes) forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source", Target = "target", Value = "value", NodeID = "name", Group = "group", opacity = 0.4)
metricsgraphics is an htmlwidget interface to the MetricsGraphics.js JavaScript/D3 chart library. […] Building metricsgraphics charts follows the "piping" idiom made popular through the magrittr, ggvis, and dplyr packages. This makes it possible to avoid one giant function with a ton of parameters and facilitates, breaking out the chart building into logical steps. While MetricsGraphics.js charts may not have the flexibility of ggplot2, you can build functional, interactive [multi-]line, scatterplot bar charts & histograms, and + even link charts together. | ||
--Bob Rudis (http://hrbrmstr.github.io/metricsgraphics/) |
After installing the required htmltools
package via CRAN, you need to install the metricsgraphics
package from GitHub:
library(devtools) install_github("hrbrmstr/metricsgraphics") library(metricsgraphics)
The following code produces a D3 scatterplot of the mtcars
dataset variables, wt
and mpg
, and adds a least square regression line within an R Markdown document. The interactivity is given by the fact that you can hover over the dots to get the exact values:
--- title: "My Interactive Report" author: "Your Name" output: html_document --- ## Using htmlwidgets & metricsgraphics ```{r} library(htmlwidgets) library(htmltools) library(metricsgraphics) ``` ```{r} # example was taken from http://rpubs.com/hrbrmstr/53741 mtcars %>% mjs_plot(x=wt, y=mpg, width=400, height=300) %>% mjs_point(least_squares=TRUE) %>% mjs_labs(x="Weight of Car", y="Miles per Gallon")