overshiny
provides draggable and resizable rectangular
elements that overlay plots in Shiny apps. This may be useful in
applications where users need to define regions on the plot for further
input or processing.
Let’s take a look at a simple user interface that includes two
overlayToken()
s, which are small labels that can be dragged
onto the plot to create new overlays, and an
overlayPlotOutput()
, which is a plot where the overlays
will appear:
library(shiny)
library(ggplot2)
library(overshiny)
# --- User interface ---
ui <- fluidPage(
titlePanel("Overlay demo"),
sidebarLayout(
sidebarPanel(
# Control whether overlays are displayed and whether they alter the plot
checkboxInput("show_overlays", "Show overlays", value = TRUE),
checkboxInput("enable_logic", "Enable overlay logic", value = TRUE),
tags$hr(),
# Select date range for the plot
dateRangeInput("date_range", "Date range", start = "2025-01-01", end = "2025-12-31"),
tags$hr(),
# Overlay controls: tokens that can be dragged onto the plot
h5("Drag tokens below onto the plot:"),
overlayToken("grow", "Grow"),
overlayToken("shrink", "Shrink")
),
mainPanel(
# Main plot with support for overlays
overlayPlotOutput("plot", width = "100%", height = 300)
)
)
)
This sets up a sidebar layout, with controls on the left (including the overlay tokens) and a display area on the right, which includes the plot the overlays will be used with.
Now let’s put together our server function. We start by setting up the overlays:
# --- App logic ---
server <- function(input, output, session)
{
# --- OVERLAY SETUP ---
# Initialise 8 draggable/resizable overlays
ov <- overlayServer("plot", 8, width = 56, # 56 days = 8 weeks default width
data = list(strength = 50), snap = snap_grid())
# Toggle overlay visibility based on checkbox
observe({
ov$show <- isTRUE(input$show_overlays)
})
The call to overlayServer()
initializes (up to) 8
overlays that we can use. It also sets the default width of new overlays
to 56, which is in plot coordinates. We’ll be plotting a time series, so
this means 56 days (8 weeks). It provides the argument
data
, which is a list of additional attributes to be
associated with each overlay. Here we’re specifying that each overlay
will have an associated strength
attribute, which we’ll use
to determine how much each overlay affects the output. And finally, we
use snap = snap_grid()
to specify a snapping function; the
default parameters for snap_grid()
ensure that each
overlay’s position and width is snapped to the nearest whole number.
Then, we start with some of the reactive logic of the overlays. We
have a checkbox in our UI to control whether the overlays are shown or
not, and the call to observe()
makes the overlays show or
hide based on the value of this checkbox.
Continuing on:
# --- OVERLAY DROPDOWN MENU ---
# Render dropdown menu when an overlay is being edited
output$plot_menu <- renderUI({
i <- req(ov$editing) # Current overlay being edited
fmt <- function(t) format(as.Date(t, origin = "1970-01-01"), "%b %d")
list(
div(paste(fmt(ov$cx0[i]), "–", fmt(ov$cx1[i]))),
selectInput("plot_label", NULL, choices = c("Grow", "Shrink"), selected = ov$label[i]),
sliderInput("plot_strength", "Strength", min = 0, max = 100, value = ov$data$strength[i]),
dateInput("plot_cx", "Start date", value = ov$cx0[i]),
sliderInput("plot_cw", "Duration", min = 1, max = floor(ov$bound_cw), value = ov$cx1[i] - ov$cx0[i])
)
})
Each overlay automatically has a dropdown menu for adjusting settings
for the overlay. By default, this only includes a “remove” button that
can be used to remove the overlay. But we can add extra elements to
these menus by using renderUI()
.
Since we created an overlayPlotOutput()
with the output
ID "plot"
, overshiny
has also created a UI
output slot named "plot_menu"
which is used to add extra
elements to each overlay’s dropdown menu. For our purposes, we’ll
include a div()
element which shows the date range for the
overlay, a selectInput()
to choose between “Grow” and
“Shrink” type overlays, and a sliderInput()
to choose the
percentage “strength” associated with the overlay. We also allow the
user to manually enter the start date of each overlay
("plot_cx"
) and the width of each overlay
("plot_cw"
). Here, "plot_label"
,
"plot_cx"
, and "plot_cw"
will automatically
set the label, position, and width of each overlay because
"label"
, "cx"
, and "cw"
are
interpreted specially by overshiny
. "strength"
doesn’t have any special interpretation so it will be applied to
ov$data$strength
. See the documentation for
overlayServer()
for more details.
The line i <- req(ov$editing)
just gets the index (1
to 8) of the current overlay being edited. The call to
req()
ensures that the rest of the code in the
renderUI()
call won’t be run unless there is an overlay
currently being edited via its dropdown menu.
Note that above, each overlay has the same elements in its dropdown menu, but we could choose to return different contents for the dropdown menu depending on which overlay is being edited.
Now let’s make some data to plot based on the overlays and their properties:
# --- DATA PROCESSING BASED ON OVERLAY POSITION ---
# Reactive dataset: oscillating signal modified by active overlays
data <- reactive({
date_seq <- seq(input$date_range[1], input$date_range[2], by = "1 day")
y <- 1 + 0.5 * sin(as.numeric(date_seq) / 58) # oscillating signal
# Modify signal according to active overlays if logic is enabled
if (isTRUE(input$enable_logic)) {
for (i in which(ov$active)) {
start <- as.Date(ov$cx0[i], origin = "1970-01-01")
end <- as.Date(ov$cx1[i], origin = "1970-01-01")
in_range <- date_seq >= start & date_seq <= end
factor <- ov$data$strength[i] / 100
y[in_range] <- y[in_range] * if (ov$label[i] == "Grow") (1 + factor) else (1 - factor)
}
}
data.frame(date = date_seq, y = y)
})
Above, we create a reactive()
data.frame. We set up a
sinusoidally-varying time series, then (if the “Enable overlay logic”
checkbox is checked) we either “grow” or “shrink” this time series where
it overlaps with each active overlay. We’re using the ov
object returned by overlayServer()
to do this.
Finally, we render the time series:
# --- RENDERING OF DATA ---
# Render plot and align overlays to current axis limits
output$plot <- renderPlot({
plot <- ggplot(data()) +
geom_line(aes(x = date, y = y)) +
ylim(0, 3) +
labs(x = NULL, y = "Signal")
overlayBounds(ov, plot, xlim = c(input$date_range), ylim = c(0, NA))
})
}
This just creates a ggplot()
plot of the time series,
and includes a call to overlayBounds()
at the end of the
renderPlot()
expression block to ensure the overlays are
aligned properly. overlayBounds()
itself returns the plot
so this also returns our plot object to Shiny to be plotted.
Now all that’s left is to run the app:
# --- Run app ---
if (interactive()) {
shinyApp(ui, server)
}