library(dplyr)
library(plotly)
<- starwars |> filter(mass < 500)
my_df
plot_ly(my_df, x = my_df$height, y = my_df$mass,
text = my_df$name,
mode = "markers", color = my_df$gender)
Easy interactive viz
{plotly} and other HTML Widgets
The ggplotly
function of the {plotly} package (Sievert 2020) is an example implementation of HTML Widgets for R. Beyond {plotly} there are many widgets to choose from. Widgets can be chained together via {crosstalk} to support cross-widget interactions such as linked brushing and filtering. The HTML widgets approach is simpler to implement than Shiny and delivers powerful interactive visualizations to your audience.
Examples
plotly
In the previous ggplot2 section on interactivity, we briefly introduced an example interactive bar chart using ggplotly
to transform a {ggplot2} object. {plotly} has its own rich syntax and can do more than make interactive ggplot2 plots. Here’s another quick example. Follow the links, above, to more documentation and examples. Try the examples below.
dygraphs
Another HTML widget is {dygraph} for time-series data
library(dygraphs)
Warning: package 'dygraphs' was built under R version 4.3.2
dygraph(nhtemp, main = "New Haven Temperatures") %>%
dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))
crosstalk and leaflet
Using {crosstalk
} for cross widget interaction (linked brushing and filtering) between two HTML widgets. In this example we link {leaflet} and {DT} widgets
Code
library(crosstalk)
library(leaflet)
library(DT)
# Wrap data frame in SharedData
<- SharedData$new(quakes[sample(nrow(quakes), 100),])
sd
# Create a filter input
filter_slider("mag", "Magnitude", sd, column=~mag, step=0.1, width=250)
Code
# Use SharedData like a dataframe with Crosstalk-enabled widgets
bscols(
leaflet(sd) %>% addTiles() %>% addMarkers(),
datatable(sd, extensions="Scroller", style="bootstrap", class="compact", width="100%",
options=list(deferRender=TRUE, scrollY=300, scroller=TRUE))
)
reactable
Or use {reactable
} another easy-to-use interactive data tables package.
library(reactable)
::mpg |>
ggplot2slice_head(n = 20) |>
reactable(searchable = TRUE, minRows = 10)
More
See more HTML widgets at the HTML Widgets for R gallery.
In the next section we’ll introduce a very powerful interactive tool that works with Quarto: ObservableJS.