# Interactive overlays in Shiny

`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("display", 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("display", 8, width = 56, # 56 days = 8 weeks default width
            data = list(strength = 50), snap = snapGrid(),
            heading = dateHeading("%b %e"), select = TRUE)

        # Toggle overlay visibility based on checkbox
        observe({
            ov$show <- isTRUE(input$show_overlays)
        })

The call to `overlayServer()` takes as its first argument the ID of the `overlayPlotOutput()` from the UI. Here, we initialize (up to) 8 overlays that we can use. We also set 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).

The `data` argument to `overlayServer()` 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. We also use `snap = snapGrid()` to specify a snapping function; the default parameters for `snapGrid()` ensure that each overlay’s position and width is snapped to the nearest whole number.

The next two arguments to `overlayServer()` relate to the overlay dropdown menus. 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 additional components to the dropdown in the call to `overlayServer()`.

The `heading` argument to `overlayServer()` allows us to add a small heading to the top of each overlay’s dropdown menu; we are using the built-in `dateHeading()` function here to specify the format of the heading. In this case, `"%b %e"` translates to the abbreviated month name followed by the day of the month. So, for example, if the overlay extends over the x-axis range 1st January to 28th February, the heading will show `"Jan 1 – Feb 28"`. Finally, the `select = TRUE` argument means that each dropdown menu will also allow us to change the type of the overlay, i.e. `"Grow"` or `"Shrink"`.

After the call to `overlayServer()`, 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
        ov$menu <- function(ov, i) {
            list(
                sliderInput("display_strength", "Strength", min = 0, max = 100, value = ov$data$strength[i]),
                dateInput("display_cx", "Start date", value = ov$cx0[i]),
                sliderInput("display_cw", "Duration", min = 1, max = floor(ov$bound_cw), value = ov$cx1[i] - ov$cx0[i])
            )
        }

Here, we add some additional, custom components to the overlay dropdown menu by assigning a function to the variable `ov$menu`. We can also pass this function in as the `menu` argument to `overlayServer()`, but the two approaches are equivalent here.

For our purposes, we’ll add 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 (`"display_cx"`) and the width of each overlay (`"display_cw"`). Here, `"display_cx"` and `"display_cw"` will automatically set the position and width of each overlay because `"cx"` and `"cw"` are interpreted specially by `overshiny`. `"strength"` doesn’t have any special interpretation so it will be applied to `ov$data$strength`. Note that the IDs of all these UI widgets start with `"display_"` because we gave our `overlayPlotOutput()` the ID `"display"` in the UI. See the documentation for `overlayServer()` for more details.

It’s important here to set the “starting value” for each of the three custom input widgets using values from the `ov` object. If we just supplied some “default” value for each of these, this value would reset each time we opened the dropdown menu.

In this example, 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 `i` 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$display <- 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)
    }