I'm working on a ggplot2
extension that works on data.frames
looking a bit like:
data <- data.frame(
type = c("text", "text", "line", "line"),
label = c("some label", "another one", NA, NA),
x = c(0,10,2,4),
y = c(0,10,3,7),
xend = c(NA, NA, 8, 10),
yend = c(NA, NA, 3, 4)
)
This means we have objects (rows) with different type
. Now I want to subset the data inside my Geoms
and Stats
based on type.
Consider the following example (using ggplot2
standard functions):
library(ggplot2)
ggplot(data, aes(x, y)) +
geom_text(aes(label = label)) +
geom_segment(aes(xend = xend, yend = yend))
This plots what one expects (text as text and lines as segments).
Now I have my own version of geom_text
called geom_var
:
GeomVar <- ggproto("GeomVar", ggplot2::GeomText,
default_aes = aes(x = x, y = y, label = label, colour = "black",
size = 4, angle = 0, hjust = 0.5, vjust = 0.5,
alpha = NA, family = "Arial", fontface = 1,
lineheight = 1.2, length = 10)
)
geom_var <- function(mapping = aes(label = label), data = NULL, position = "identity",
..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE,
na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
{
ggplot2::layer(data = data, mapping = mapping, stat = StatVar, geom = GeomVar,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(parse = parse, check_overlap = check_overlap,
na.rm = na.rm, ...))
}
StatVar <- ggproto("StatVar", ggplot2::Stat,
compute_group = function(data, scales, length = 5) {
data$label <- sapply(data$label,
function(x) {paste0(strwrap(x, width = length),
collapse = "\n")})
data
}
)
stat_var <- function(mapping = NULL, data = NULL, geom = "var",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
ggplot2::layer(
stat = StatVar, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
When I use my own version the plot looks like:
ggplot(data, aes(x, y)) +
geom_var(aes(label = label)) +
geom_segment(aes(xend = xend, yend = yend))
TL;DR:
How can I change my
GeomVar
and/orStatVar
in order the NAs don't get plotted anymore?Or: How can I subset my
data
based ontype
in myGeomVar
andStatVar
functions?
(I tried data <- data[data$type == "text", ]
in basically every place data
occurs in the GeomVar
, geom_var
, StatVar
and stat_var
functions..)