Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom Stat object in ggplot2

Tags:

r

ggplot2

I'd like to create a custom Stat object for ggplot2. (Specifically I'd like to create a smoother that works differently than the ones stat_smooth allows- for instance, without a y~x modeling function- but there are other custom Stats I'd like to create even if there were a workaround for my specific case).

I found this suggested solution from Hadley Wickham:

StatExpo <- proto(Stat, {
  objname <- "expo"
  desc <- "Exponential smoothing"
  default_geom <- function(.) GeomLine

  calculate_groups <- function(., data, scales, variable="x", ...) {
    data$y <- HoltWinters(data$x, ...)
  }
})
stat_expo <- StatExpo$new

However, when I try it I get:

Error in proto(Stat, { : object 'Stat' not found

Upon looking around the ggplot code, I found where Stat is defined. However, the Stat object is, as far as I can tell, never exported from ggplot2.

I could write my new stat object within the ggplot2/R folder and then reinstall the package, but obviously this would be cumbersome and make the solution very difficult to share with others. How can I create a custom Stat object outside of the ggplot namespace?

like image 362
David Robinson Avatar asked Aug 07 '13 16:08

David Robinson


2 Answers

ggplot2:::Stat can be used to access the non-exported object.

like image 156
baptiste Avatar answered Sep 22 '22 05:09

baptiste


getFromNamespace('Stat','ggplot2')
like image 32
Nicholas Hamilton Avatar answered Sep 21 '22 05:09

Nicholas Hamilton