Chapter 4 Interactive visualization

In DS-6030, we will not use interactive visualizations. However, it can be useful to explore data interactively. In this section, we will briefly discuss how to create interactive visualizations in R using the plotly package.

The package plotly allows to embed interactive plots in R Markdown documents. The package is available on CRAN and can be installed as follows:

install.packages("plotly", repos="http://cran.rstudio.com")

and loaded using:

Code
library(plotly)

4.1 Add interactivity to ggplot figure using ggplotly

A convenient way of using plotly is to use the ggplotly() function, which converts a ggplot2 plot into a plotly object. For example, the following code creates a scatterplot of mpg versus horsepower from the Auto data set and converts it into an interactive plot:

Code
Auto = ISLR2::Auto %>%
    mutate(cylinders = as.factor(cylinders))

g <- ggplot(Auto, aes(x=horsepower, y=mpg, label=name)) +
    geom_point()

ggplotly(g) 

Figure 4.1: Interactive scatterplot of mpg versus horsepower

The resulting plot can be zoomed and dragged. Hovering over a point displays information about the car.

4.2 Three dimensional plots using plot_ly

A three dimensional plot can be created as shown in the following example.

Code
plot_ly(x=Auto$mpg, y=Auto$weight, z=Auto$horsepower, color=Auto$cylinders, 
        type="scatter3d", mode="markers", 
        marker=list(size=4))

Figure 4.2: Interactive 3D scatterplot of mpg versus horsepower and weight

Further information:

Code

The code of this chapter is summarized here.

Code
knitr::opts_chunk$set(echo=TRUE, cache=TRUE, autodep=TRUE, fig.align="center")
library(plotly)
Auto = ISLR2::Auto %>%
    mutate(cylinders = as.factor(cylinders))

g <- ggplot(Auto, aes(x=horsepower, y=mpg, label=name)) +
    geom_point()

ggplotly(g) 
plot_ly(x=Auto$mpg, y=Auto$weight, z=Auto$horsepower, color=Auto$cylinders, 
        type="scatter3d", mode="markers", 
        marker=list(size=4))