Chapter 12 Interactive Graphs

This book has focused on static graphs - images that can be placed in papers, posters, slides, and journal articles. Through connections with JavaScript libraries, R can also generate interactive graphs that can be placed on web pages.

Interactive graphics are beyond the scope of this book. This chapter will point out some of the best options, so you can explore them further. Most use htmlwidgets for R.

Note that if your are reading this on an iPad, some features will not be available (such as mouseover).

12.1 leaflet

Leaflet is a javascript library for interactive maps. The leaflet package can be used to generate leaflet graphs R.

The following is a simple example. Click on the pin, zoom in and out with the +/- buttons or mouse wheel, and drag the map around with the hand cursor.

# create leaflet graph
library(leaflet)
leaflet() %>%
  addTiles() %>%
  addMarkers(lng=-72.6560002, 
             lat=41.5541829, 
             popup="The birthplace of quantitative wisdom.</br>
             No, Waldo is not here.")

Figure 12.1: Leaflet graph

You can create both dot density and choropleth maps. The package website offers a detailed tutorial and numerous examples.

12.2 plotly

Plotly is both a commercial service and open source product for creating high end interactive visualizations. The plotly package allows you to create plotly interactive graphs from within R. In addition, any ggplot2 graph can be turned into a plotly graph.

Using the Fuel Economy data, we’ll create an interactive graph displaying highway mileage vs. engine displace by car class.

Mousing over a point displays information about that point. Clicking on a legend point, removes that class from the plot. Clicking on it again, returns it.

# create plotly graph.
library(ggplot2)
library(plotly)

p <- ggplot(mpg, aes(x=displ, 
                     y=hwy, 
                     color=class)) +
  geom_point(size=3) +
  labs(x = "Engine displacement",
       y = "Highway Mileage",
       color = "Car Class") +
  theme_bw()

ggplotly(p)

Figure 12.2: Plotly graph

There are several sources of good information on plotly. See the plotly R pages and the online plotly for R book. Additionally, DataCamp offers a free interactive tutorial.

12.3 rbokeh

rbokeh is an interface to the Bokeh graphics library.

We’ll create another graph using the mtcars dataset, showing engine displace vs. miles per gallon by number of engine cylinders. Mouse over, and try the various control to the right of the image.

# create rbokeh graph

# prepare data
data(mtcars)
mtcars$name <- row.names(mtcars)
mtcars$cyl <- factor(mtcars$cyl)

# graph it
library(rbokeh)
figure() %>%
  ly_points(disp, mpg, data=mtcars,
            color = cyl, glyph = cyl,
            hover = list(name, mpg, wt))

Figure 12.3: Bokeh graph

You can create some remarkable graphs with Bokeh. See the homepage for examples.

12.4 rCharts

rCharts can create a wide range of interactive graphics. In the example below, a bar chart of hair vs. eye color is created. Try mousing over the bars. You can interactively choose between grouped vs. stacked plots and include or exclude cases by eye color.

# create interactive bar chart
library(rCharts)
hair_eye_male = subset(as.data.frame(HairEyeColor), 
                       Sex == "Male")
n1 <- nPlot(Freq ~ Hair, 
            group = 'Eye', 
            data = hair_eye_male, 
            type = 'multiBarChart'
)
n1$set(width = 600)
n1$show('iframesrc', cdn=TRUE)

To learn more, visit the project homepage.

12.5 highcharter

The highcharter package provides access to the Highcharts JavaScript graphics library. The library is free for non-commercial use.

Let’s use highcharter to create an interactive line chart displaying life expectancy over time for several Asian countries. The data come from the Gapminder dataset. Again, mouse over the lines and try clicking on the legend names.

# create interactive line chart
library(highcharter)

# prepare data
data(gapminder, package = "gapminder")
library(dplyr)
asia <- gapminder %>%
  filter(continent == "Asia") %>%
  select(year, country, lifeExp)

# convert to long to wide format
library(tidyr)
plotdata <- spread(asia, country, lifeExp)

# generate graph
h <- highchart() %>% 
  hc_xAxis(categories = plotdata$year) %>% 
  hc_add_series(name = "Afghanistan", 
                data = plotdata$Afghanistan) %>% 
  hc_add_series(name = "Bahrain", 
                data = plotdata$Bahrain) %>%
  hc_add_series(name = "Cambodia", 
                data = plotdata$Cambodia) %>%
  hc_add_series(name = "China", 
                data = plotdata$China) %>%
  hc_add_series(name = "India", 
                data = plotdata$India) %>%
  hc_add_series(name = "Iran", 
                data = plotdata$Iran)

h

Figure 12.4: HighCharts graph

Like all of the interactive graphs in this chapter, there are options that allow the graph to be customized.

# customize interactive line chart
h <- h %>%
  hc_title(text = "Life Expectancy by Country",
           margin = 20, 
           align = "left",
           style = list(color = "steelblue")) %>% 
  hc_subtitle(text = "1952 to 2007",
              align = "left",
              style = list(color = "#2b908f", 
                           fontWeight = "bold")) %>% 
  hc_credits(enabled = TRUE, # add credits
             text = "Gapminder Data",
             href = "http://gapminder.com") %>% 
  hc_legend(align = "left", 
            verticalAlign = "top",
            layout = "vertical", 
            x = 0, 
            y = 100) %>%
  hc_tooltip(crosshairs = TRUE, 
             backgroundColor = "#FCFFC5",
             shared = TRUE, 
             borderWidth = 4) %>% 
  hc_exporting(enabled = TRUE)

h

Figure 12.5: HighCharts graph with customization

There is a wealth of interactive plots available through the marriage of R and JavaScript. Choose the approach that works for you.