The following R code shows a demo ggplot2 extension. This extension displays a star at a specified x-axis group (option ref.group
).
In the StatShowStarsAt
ggproto code, the user specified ref.group
is mapped to the transformed data value in the aesthetic space, using ref.group <- scales$x$map(ref.group)
.
For grouped plots, does something similar exist for mapping legend group in the aesthetic space? For example, legend.group <- scales$legend$map(legend.group)
, where legend.group can be color or fill scale.
# ggplot2 extension: demo
library(ggplot2)
stat_show_stars_at <- function(mapping = NULL, data = NULL, geom = "text", position = "identity",
na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ref.group = NULL, ...){
layer(
stat = StatShowStarsAt, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(ref.group = ref.group, ...)
)
}
StatShowStarsAt <- ggproto("StatShowStarsAt", Stat,
required_aes = c("x", "y"),
compute_panel = function(self, data, scales, ref.group)
{
if(!is.null(ref.group)) {
ref.group <- scales$x$map(ref.group)
}
data.frame(
x = ref.group,
y = scales$y$range$range[2],
label = "*"
)
}
)
# Usage
ggplot(PlantGrowth, aes(group, weight)) +
geom_boxplot() +
stat_show_stars_at(ref.group = "trt2", color = "red", size = 10)