Extending existing ggplot2 stat function

Hi

Section 21 of Hadley's ggplot2 book describes how to create new stat/geom including the case in which one extends an existing stat/geom. Hadley writes about ggplot2:::GeomSpoke which augments ggplot2:::GeomSegment by replacing the setup_data() inner function.

In my case, I would like to augment ggplot2::StatBin by adding variables to the bins object which is the output of the inner compute_group() function. Rather than rewriting the entire compute_group() function of my new ggproto, I would like to first call the compute_group() function of ggplot2::StatBin then add my variables.

My naive attempt below does not work. An error 'object of type closure is not subsettable is returned in the step where I try to call the compute_group() function.

StatBin2 <- ggrplot2::ggproto(
  "StatBin2",
  ggplot2::StatBin,
  compute_group = function(data, scales, binwidth = NULL, bins = NULL, center = NULL, 
    boundary = NULL, closed = c("right", "left"), pad = FALSE, 
    breaks = NULL, flipped_aes = FALSE, origin = NULL, right = NULL, 
    drop = NULL, width = NULL){
    # Call compute_group from StatBin 
    bins <- ggplot2::StatBin$compute_group(data=data, scales=scales, binwidth = binwidth,  
      bins = bins, center = center, boundary = boundary, closed = closed, pad = pad, 
      breaks = breaks, flipped_aes = flipped_aes, origin = origin, right = right, 
      drop = drop, width = width)

    # Add my variables
    bins$foo <- 'bar'
    bins
  }
)

Any suggestion on the proper way to call an inner function of a ggproto object would be welcome.

Thanks in advance for your time.

Found it:

fun <- ggplot2:::fetch_ggproto(ggplot2::StatBin, 'compute_group')

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.