ggplot2使用映射的AES覆盖固定的美感

时间:2019-02-22 14:33:37

标签: r ggplot2

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()

enter image description here

## Try to override colour with aes mapping: doesn't work
p + stat_sum_df(mapping = aes(colour = Species))
# same as above

enter image description here

这是可以解决的,但是我不确定这是否是最可靠的方法:

## 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))

enter image description here

0 个答案:

没有答案