drop_vars | R Documentation |
Automatically remove unused variables from the "default" data object embedded
in a gg
or ggplot
object with drop_vars()
. Explore data
variables and their use with mapped_vars()
, data_vars()
and
data_attributes()
.
drop_vars(p, keep.vars = character(), guess.vars = TRUE)
mapped_vars(p, invert = FALSE)
data_vars(p)
data_attributes(p)
p |
ggplot Plot object with embedded data. |
keep.vars |
character Names of unused variables to be kept. |
guess.vars |
logical Flag indicating whether to find used variables automatically. |
invert |
logical If TRUE return indices for elements of |
A "ggplot"
object that is a copy of p
but containing
only a subset of the variables in its default data
.
character vector with names of mapped variables in the default data object.
character vector with names of all variables in the default data object.
list containing all attributes of the default data object.
The current implementation drops variables only from the default data object. Data objects within layers are not modified.
These functions are under development and not yet thoroughly tested!
They are a demonstration of how one can manipulate the internals of
ggplot
objects creayed with 'ggplot2' versions 3.1.0 and later.
These functions may stop working after some future update to the 'ggplot2'
package. Although I will maintain this package for use in some of my other
packages, there is no guarantee that I will be able to achieve this
transparently.
Obviously, rather than using function drop_vars()
after creating the
ggplot
object it is usually more efficient to select the variables
of interest and pass a data frame containing only these to the
ggplot()
constructor.
library(ggplot2)
p <- ggplot(mpg, aes(factor(year), (cty + hwy) / 2)) +
geom_boxplot() +
facet_grid(. ~ class)
mapped_vars(p) # those in use
mapped_vars(p, invert = TRUE) # those not used
p.dp <- drop_vars(p) # we drop unused vars
# number of columns in the data member
ncol(p$data)
ncol(p.dp$data)
# which vars are in the data member
data_vars(p)
data_vars(p.dp)
# which variables in data are used in the plot
mapped_vars(p)
mapped_vars(p.dp)
# the plots identical
p
p.dp
# structure and size of p
str(p, max.level = 0)
str(p.dp, max.level = 0) # smaller in size
# structure and size of p["data"]
str(p, components = "data")
str(p.dp, components = "data") # smaller in size
# shape data
if (requireNamespace("sf", quietly = TRUE)) {
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
p.sf <- ggplot(data = nc) +
geom_sf()
p.sf
mapped_vars(p.sf)
drop_vars(p.sf)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.