Acessing raw data from custom ggplot2 layer

Hi everyone,

I'm trying to extend ggplot2 with a custom stat_* method that depends on the x values being of a specific type. However, ggplot2 does not preserve them and rather seems to coerce them to a numeric type. My naive approach would be to access the data as early as possible

Consider using the circular package:

data = data.frame (x = circular(c(14,167,245,341), units = "degree"))
print(class(data$x)) # [1] "circular" "numeric" 

If I now want to access data$x within the compute_group() function, it has already been coerced to numeric:

[...],
compute_group = function(self, data, scales, offset = 1) {
          print(class(data$x)) # [1] "numeric"
}, [...]

I basically want a way to either preserve the class (and the column's attributes) or to access the data before coercing to numeric so that I can set parameters based on them.

Is there any elegant way of doing this? I could always use a custom ggplot() function, but that seems a little over the top.

Here is a runnable example:

library(circular)
library(tidyverse)

## StatDensityCircular
StatDensityCircular <- ggproto("StatDensityCircular", Stat,
                               compute_group = function(self, data, scales, offset = 1) {
                                 print(class(data$x)) # already numeric
                                 # do some computations here ...
                               },
                               required_aes = c("x")
)

stat_density_circular <- function(mapping = NULL, data = NULL, geom = "line",
                                  position = "identity", na.rm = FALSE, show.legend = NA,
                                  inherit.aes = TRUE, ...) {
  layer(
    stat = StatDensityCircular, data = data, mapping = mapping, geom = geom, 
    position = position, show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(na.rm = na.rm, ...)
  )
}


data = data.frame (x = circular(c(14,167,245,341), units = "degree") )

ggplot(data=data, aes(x=x)) +
  stat_density_circular()

Cheers,
Marc

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.