--- title: Adding htmlwidgets to R Markdown posts date: '2017-09-07' slug: adding-htmlwidgets-to-r-markdown-posts raw: "https://raw.githubusercontent.com/rbind/blogdown-demo/master/content/post/2017-09-07-adding-htmlwidgets-to-r-markdown-posts.Rmd" --- ```{r setup, include = FALSE} knitr::opts_chunk$set(comment = NA, tidy = FALSE, warning = FALSE, message = FALSE) ``` This is a minimal example of how to use [htmlwidgets](http://www.htmlwidgets.org/index.html) in R Markdown posts. We will use a tidy version of Anscombe's quartet (thanks to [David Robinson](https://rpubs.com/dgrtwo/tidy-anscombe)). To reshape the anscombe dataset, you will need the **dplyr** and **tidyr** packages loaded. You'll also need to install and load the **DT** package for example 1, and the **ggplot2** and **plotly** packages for example 2. ```{r} library(dplyr) library(tidyr) library(DT) library(ggplot2) library(plotly) anscombe_tidy <- anscombe %>% mutate(observation = seq_along(x1)) %>% gather(key, value, -observation) %>% separate(key, c("variable", "set"), 1, convert = TRUE) %>% mutate(set = as.character(as.roman(set))) %>% spread(variable, value) %>% arrange(set) head(anscombe_tidy) ``` Now that it has been reshaped, we can view and plot Anscombe's quartet in our post. # Example 1: DataTables via the **DT** package We can interactively view the tidied Anscombe's quartet using the **DT** package: ```{r} anscombe_tidy %>% datatable(rownames = FALSE, options = list( pageLength = 11, autoWidth = TRUE, columnDefs = list(list( className = 'dt-left', targets = 0), list(className = 'dt-center', targets = 1)))) ``` # Example 2: Using the **plotly** package We can also interactively plot the tidied Anscombe's quartet using the **plotly** package (you will need the **ggplot2** package loaded here): ```{r} cols <- c("#0072B2", "#009E73", "#D55E00", "#CC79A7") ans_plot <- ggplot(anscombe_tidy, aes(x, y, colour = set)) + geom_point(size = 3, alpha = .7) + geom_smooth(method = "lm", se = FALSE) + facet_wrap(~ set) + theme_bw() + theme(legend.position="none") + scale_colour_manual(values = cols) ggplotly(ans_plot) ```