Tom Hopper
2014-Mar-03 14:37 UTC
[R] Replacing a plotting function in a package with a ggplot2 version
I?ve been working on a home-brewed version of the plot function in the package
qcc that would be more compatible with grid graphics. I?d like to share this
with the R community, in the hopes that this reference helps some of my fellow
learners. The issues that I overcame were all documented elsewhere, but not
always easy to find; hopefully this helps with the search engines.
I have written a replacement for the plot.qcc() function in the qcc package.
Features that may be of interest:
* The new plot function generates graphs almost identical to the original base
graphic versions, but using ggplot2, gtable and grid. Some of the differences in
programming technique are documented (e.g. the need to pass data frames rather
than individual vectors to ggplot). Several issues were overcome, including the
search scope of aes() and the use of aes_string() versus aes(), especially when
using ggplot within a function.
* The new function replaces plot.qcc() in the qcc namespace, so that after
calling source() with my code, all calls to plot() with a qcc object draw the
new ggplot2-based version. The code demonstrates how to unbind an existing
function and bind a new function in its place within the package namespace using
the following code:
unlockBinding(sym="plot.qcc", env=getNamespace("qcc"));
assignInNamespace(x="plot.qcc", value=plot.qcc,
ns=asNamespace("qcc"), envir=getNamespace("qcc"));
assign("plot.qcc", plot.qcc, envir=getNamespace("qcc"));
lockBinding(sym="plot.qcc", env=getNamespace("qcc"));
* Finally, the code shows how to annotate a plot outside the data panel, when
the labels need to be aligned with the data (e.g. plot a reference line with
geom_hline() and then annotate a label for the line to the right of the plot).
This implementation might not be the most elegant or bug-free, but it has passed
my testing so far.
The code is available on Github at https://github.com/tomhopper/gcc_ggplot/
Best Regards,
Tom Hopper
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 670 bytes
Desc: Message signed with OpenPGP using GPGMail
URL:
<https://stat.ethz.ch/pipermail/r-help/attachments/20140303/9e7873d6/attachment.bin>