Skip to contents

This function creates a ggplot2 layer that shades date ranges based on grouped data. It's particularly useful for highlighting specific periods in time series data.

Usage

stat_shade_ranges(
  mapping = NULL,
  data = NULL,
  geom = "linerange",
  position = "identity",
  na.rm = TRUE,
  show.legend = NA,
  inherit.aes = TRUE,
  ...
)

Arguments

mapping

Set of aesthetic mappings created by aes. Must include `x` for dates and `group` for categorizing ranges.

data

The data to be displayed in this layer. If NULL, the default, the data is inherited from the plot data as specified in the call to ggplot.

geom

The geometric object to use display the data. Default is "linerange".

position

Position adjustment, either as a string, or the result of a call to a position adjustment function. Default is "identity".

na.rm

If FALSE, the default, missing values are removed with a warning. If TRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends? NA, the default, includes if any aesthetics are mapped.

inherit.aes

If FALSE, overrides the default aesthetics, rather than combining with them.

...

Other arguments passed on to layer. These are often aesthetics, used to set an aesthetic to a fixed value.

Value

A ggplot2 layer object.

Examples

if (FALSE) {
library(ggplot2)
library(data.table)

# Create sample data
dt <- data.table(
    datetime = seq(as.POSIXct("2023-01-01"), as.POSIXct("2023-12-31"), by = "day"),
    close = runif(365, 100, 200),
    call = sample(c("buy", "sell", "none"), 365, replace = TRUE, prob = c(0.3, 0.3, 0.4))
)

# Create plot with shaded ranges
ggplot(dt, aes(x = datetime)) +
    geom_line(aes(y = close), linewidth = 1.5, colour = "white") +
    stat_shade_ranges(aes(group = call, fill = call), alpha = 0.25) +
    scale_fill_manual(
        name = "Call",
        values = c("buy" = "green", "sell" = "red", "none" = "gray")
    ) +
    theme_minimal() +
    labs(title = "Stock Price with Buy/Sell Signals", x = "Date", y = "Price")
}