Some notes on extending ggplot2 using custom grid grobs

For the directlabels package, since there is not a lot of documentation on extending ggplot2, I had to look through the code quite a bit to understand how it works. This document tries to summarize a few things I learned in this process that can be applicable to writing geoms in the future.

First, download the most recent version of the ggplot2 source from github:

cd
mkdir R
cd R
git clone git://github.com/hadley/ggplot2.git

Then you can look at how the geoms are implemented, in ggplot2/R/geom-*.r. For directlabels, I basically modified GeomText in geom-text.r.

The most important method is draw (from directlabels/R/ggplot2.R):

GeomDirectLabel <- proto(Geom, {
  draw <- function(., data, scales, coordinates,
                   method=NULL,debug=FALSE, ...) {
    data$rot <- as.integer(data$angle)
    data$groups <- data$label
    dlgrob(subset(coordinates$transform(data, scales),select=-group),
           method,debug=debug,
           axes2native=function(data){
             coordinates$transform(data, scales)
           })
  }
})

Author: Toby HOCKING

Org version 7.5 with Emacs version 22

Validate XHTML 1.0