teunbrand / ggh4x

ggplot extension: options for tailored facets, multiple colourscales and miscellaneous
https://teunbrand.github.io/ggh4x/
Other
542 stars 33 forks source link

Run length encoding stat #12

Closed teunbrand closed 4 years ago

teunbrand commented 4 years ago

To do basically this, but then in a stat function:

library(ggplot2)

df <- data.frame(
  x = seq(0, 10, length.out = 100),
  y = sin(seq(0, 10, length.out = 100))
)

rle <- rle(df$y > 0.5)
start <- {end <- cumsum(rle$lengths)} - rle$lengths + 1

df2 <- data.frame(
  xmin = df$x[start],
  xmax = df$x[end],
  value = rle$values
)

ggplot(df) +
  geom_rect(data = df2, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, fill = value)) +
  geom_point(aes(x, y))

Created on 2020-05-22 by the reprex package (v0.3.0)

teunbrand commented 4 years ago

This now works:

library(ggplot2)
library(ggh4x)

df <- data.frame(
    x = seq(0, 10, length.out = 100),
    y = sin(seq(0, 10, length.out = 100)*2)
)

ggplot(df) +
    stat_rle(aes(x, label = y > 0.5),
             align = "center") +
    geom_point(aes(x, y))

Created on 2020-06-02 by the reprex package (v0.3.0)