Skip to content

Instantly share code, notes, and snippets.

@russellpierce
Last active August 18, 2017 17:39
Show Gist options
  • Select an option

  • Save russellpierce/6549980 to your computer and use it in GitHub Desktop.

Select an option

Save russellpierce/6549980 to your computer and use it in GitHub Desktop.
Get all values along a given axis from a ggplot2 object (including layers).
# Get all variables plotted along a given axis in a ggplot.
getPlottedVals <- function(ggplotObj,axis=c("x","y"),includeLayers=TRUE)
{
if (is.null(axis)) {stop("In getPlotted: Argument axis not specified.")}
getValAxis <- function(.q,axis=c("x","y")) {
as.data.table(.q$data)[,eval(.q$mapping[[axis]])]
}
getLayerAxis <- function(tmpLayer,axis=c("x","y")) {
if (!any(class(tmpLayer$data) %in% "waiver") & (any(class(tmpLayer$data)=="data.frame"))) {
return(getValAxis(tmpLayer,axis))
} else {return(NULL)}
}
res <- getValAxis(ggplotObj,axis=axis)
if (includeLayers) {res <- c(res,unlist(lapply(ggplotObj$layer,getLayerAxis,axis=axis)))}
return(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment