Lecture 10: Interactive Visualization of Data

plotly package

Author
Affiliation

Jihong Zhang*, Ph.D

Educational Statistics and Research Methods (ESRM) Program*

University of Arkansas

Published

March 19, 2025

Overview

  • Introduction to Plotly
  • Advanced Plot Types
  • Customization Techniques
  • Interactivity Features
  • Integration with Other Tools
  • Performance Optimization

Introduction to Plotly

  1. Plotly is an open-source JavaScript library that enables the creation of interactive, publication-quality plots in R. It supports various chart types, including line plots, scatter plots, bar charts, histograms, and more. Interactive plots enhance data exploration and presentation by allowing users to engage directly with visualizations.

  2. The plotly package is built on top of the htmlwidgets framework, which allows R users to create interactive web-based visualizations using JavaScript libraries.

plotly package

Basic Information

plotly R package is powered by the Javascript libray plotly.js. A plotly object is intialized with a plot_ly() function.

library(plotly)
library(ggplot2)
head(diamonds)
# A tibble: 6 × 10
  carat cut       color clarity depth table price     x     y     z
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
Note
  • Within below code block, plot_ly() tries to find a sensible geometric representation of that information for

  • Note that column name is formated with ~Name in plot_ly(), which is different from ggplot2 package Name or vars(Name).

plot_ly(diamonds, x=~cut)
plot_ly(diamonds, x=~cut, y=~clarity, colors="Accent")
plot_ly(diamonds, x=~cut, color=~clarity, colors="Accent")

Plot 1

Plot 2

Plot 3

  • To specify the color directly, use I() function to declar the color value as “asis”.
plot_ly(diamonds, x=~cut, 
        color=I("tomato"), 
        stroke=I("royalblue"), 
        span = I(3)) |> 
layout(title = "Histogram with I() function")

Translate ggplot2 to plotly

In Figure 1, ggplotly() can translate a ggplot2 object into a plotly object.

p <- ggplot(diamonds, aes(x=log(carat), y=log(price))) + 
  geom_hex(bins = 100)
ggplotly(p)
Figure 1

add_ as layers and |> as connection

Plotly implements geoms in a similar fashion as ggplot2, functions that start in add_ add a layer to the plot (e.g.: add_lines, add_bars), making it easy to combine series into a single chart, as in Figure 2.

plot_ly(mtcars, x=~disp) |> 
  add_markers(y=~mpg, text = rownames(mtcars)) |> 
  add_lines(y=~fitted(loess(mpg ~ disp)))
Figure 2: Plotly with add_ and |> as connection

Advanced Plot Types

3D Scatter and Surface Plots

Visualizing three-dimensional data can provide deeper insights into complex datasets.

library(plotly)

# Sample data
x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)

# 3D Scatter Plot
fig <- plot_ly(x = ~x, y = ~y, z = ~z, type = 'scatter3d', mode = 'markers')
fig

Heatmaps and Contour Plots

Heatmaps and contour plots are effective for representing data density and gradients.

# Sample data
z <- matrix(rnorm(100), nrow = 10)

# Heatmap
heatmap <- plot_ly(z = ~z, type = 'heatmap')
heatmap

Customization Techniques

Theming and Templates

Utilizing pre-defined themes and creating custom templates ensures consistent styling across multiple plots.

# Sample data
x <- c('A', 'B', 'C')
y <- c(10, 15, 13)

# Manually setting dark theme colors
fig <- plot_ly(x = ~x, y = ~y, type = 'bar', 
               marker = list(color = 'lightblue')) |>
  layout(title = list(text = 'Custom Themed Bar Chart', 
                      font = list(color = 'white')),
         plot_bgcolor = 'black',
         paper_bgcolor = 'black',
         font = list(color = 'white'))

fig

Annotations and Shapes

Adding informative annotations and geometric shapes can highlight significant data points or regions.

# Sample data
x <- c(1, 2, 3, 4)
y <- c(10, 11, 12, 13)

# Line Plot with Annotation
fig <- plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'lines') |>
  layout(title = 'Annotated Line Plot',
         annotations = list(
           x = 2, y = 11, text = "Important Point", showarrow = TRUE
         ))
fig

Interactivity Features

Hover and Click Events

Interactive features such as hover and click events can display additional information or trigger specific actions upon user interaction.

# Sample data
x <- c('A', 'B', 'C')
y <- c(10, 15, 13)

# Bar Chart with Hover Info
fig <- plot_ly(x = ~x, y = ~y, type = 'bar', text = ~paste('Value: ', y),
               hoverinfo = 'text')
fig

Sliders and Dropdowns

Incorporating interactive controls like sliders and dropdowns allows users to dynamically filter or modify the data displayed.

# Sample data
x <- c(1, 2, 3, 4, 5)
y1 <- c(1, 3, 5, 7, 9)
y2 <- c(2, 4, 6, 8, 10)

# Line Plot with Dropdown
fig <- plot_ly() |>
  add_trace(x = ~x, y = ~y1, type = 'scatter', mode = 'lines', name = 'Line 1') |>
  add_trace(x = ~x, y = ~y2, type = 'scatter', mode = 'lines', name = 'Line 2') |>
  layout(
    title = 'Line Plot with Dropdown',
    updatemenus = list(
      list(
        y = 0.8,
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(TRUE, FALSE)),
               label = "Line 1"),
          list(method = "restyle",
               args = list("visible", list(FALSE, TRUE)),
               label = "Line 2"),
          list(method = "restyle",
               args = list("visible", list(TRUE, TRUE)),
               label = "Both")
        )
      )
    )
  )
fig

Integration with Other Tools

Shiny Applications

Integrating Plotly plots within Shiny apps enables the development of interactive web applications.

library(shiny)


ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlotly({
    plot_ly(x = ~rnorm(100), type = 'histogram')
  })
}

shinyApp(ui, server)

R Markdown

Embedding interactive plots in R Markdown documents facilitates dynamic reporting.

---
title: "Interactive Plot in R Markdown"
output: html_document
---

Performance Optimization

Efficient Data Handling

Managing large datasets effectively ensures responsive and efficient plotting.

# Sample large data
x <- rnorm(1e6)

# Histogram with Binning
fig <- plot_ly(x = ~x, type = 'histogram', nbinsx = 100)
fig