12 min read

Adding htmlwidgets to R Markdown posts


View raw source for this post

This is a minimal example of how to use htmlwidgets in R Markdown posts. We will use a tidy version of Anscombe’s quartet (thanks to David Robinson). 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.

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)
  observation set  x    y
1           1   I 10 8.04
2           2   I  8 6.95
3           3   I 13 7.58
4           4   I  9 8.81
5           5   I 11 8.33
6           6   I 14 9.96

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:

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):

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)