对stat_summary
函数进行编程时,有一种方法可以覆盖预先编程的外观:
library(ggplot2)
## Make base plot
p <- ggplot(data = iris, aes(Species, Sepal.Length)) +
geom_point()
## Define function for stat summary
stat_sum_df <- function(fun = median, geom="point", colour = "red", ...) {
stat_summary(fun.y = fun, colour = colour, geom = geom, size = 4, ...)
}
## Add summary stat to plot
p + stat_sum_df()
## Try to override colour with aes mapping: doesn't work
p + stat_sum_df(mapping = aes(colour = Species))
# same as above
这是可以解决的,但是我不确定这是否是最可靠的方法:
## Hack?
stat_sum_hack <- function(fun = median, geom = "point", colour = "red", ...) {
params <- list(...)
if ("mapping" %in% names(params)) {
stat_summary(fun.y = fun, geom = geom, size = 4, ...)
} else {
stat_summary(fun.y = fun, colour = colour, geom = geom, size = 4, ...)
}
}
p + stat_sum_hack(mapping = aes(colour = Species))