Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

remove_geom: a function to remove layers from a ggplot2 object

  • Loading branch information...
commit 18224d14b84f3dd7e1c39bec42012ad2daf3ddb3 1 parent 3af088f
erik 'quantitative warlock' shilts authored
View
1  DESCRIPTION
@@ -205,3 +205,4 @@ Collate:
'translate-qplot-lattice.r'
'annotation-logticks.r'
'utilities-help.r'
+ 'remove-geom.R'
View
1  NAMESPACE
@@ -289,6 +289,7 @@ export(position_stack)
export(qplot)
export(quickplot)
export(rel)
+export(remove_geom)
export(resolution)
export(scale_alpha)
export(scale_alpha_continuous)
View
3  NEWS
@@ -1,6 +1,9 @@
ggplot2 0.9.3.99
----------------------------------------------------------------
+* New function `remove_geom` to remove specific layers from a ggplot2
+ object.
+
BUG FIXES
* The theme element `legend.box.just` now can be set. It was not properly
View
28 R/remove-geom.R
@@ -0,0 +1,28 @@
+#' Remove a Geom From a ggplot2 Object
+#'
+#' remove_geom allows you to remove layers of from a ggplot2 object
+#' by specifying the name of a geom to remove. This can be useful
+#' when dynamically building ggplot2 objects and want to remove
+#' cluttered layers that have already been added to the object in
+#' previous function calls.
+#'
+#' @param plot_object the ggplot2 object to work on
+#' @param geom name of geom to remove
+#' @examples
+#' p <- ggplot(data.frame(a=1:10, b=1:10), aes(x=a, y=b)) + geom_point() + geom_line()
+#' p_minus_point <- remove_geom(p, "point")
+#' stopifnot(
+#' setdiff(
+#' sapply(p$layers, function(x) x$geom$objname),
+#' sapply(p_minus_point$layers, function(x) x$geom$objname)
+#' ) == "point"
+#' )
+#' @export
+remove_geom <- function(plot_object, geom) {
+
+ layers <- lapply(plot_object$layers, function(x) if(x$geom$objname == geom) NULL else x)
+ layers <- layers[!sapply(layers, is.null)]
+
+ plot_object$layers <- layers
+ plot_object
+}
View
29 man/remove_geom.Rd
@@ -0,0 +1,29 @@
+\name{remove_geom}
+\alias{remove_geom}
+\title{Remove a Geom From a ggplot2 Object}
+\usage{
+ remove_geom(plot_object, geom)
+}
+\arguments{
+ \item{plot_object}{the ggplot2 object to work on}
+
+ \item{geom}{name of geom to remove}
+}
+\description{
+ remove_geom allows you to remove layers of from a ggplot2
+ object by specifying the name of a geom to remove. This
+ can be useful when dynamically building ggplot2 objects
+ and want to remove cluttered layers that have already
+ been added to the object in previous function calls.
+}
+\examples{
+p <- ggplot(data.frame(a=1:10, b=1:10), aes(x=a, y=b)) + geom_point() + geom_line()
+p_minus_point <- remove_geom(p, "point")
+stopifnot(
+ setdiff(
+ sapply(p$layers, function(x) x$geom$objname),
+ sapply(p_minus_point$layers, function(x) x$geom$objname)
+ ) == "point"
+)
+}
+
Please sign in to comment.
Something went wrong with that request. Please try again.