有几种方法可以做到这一点,尽管要获得像+ mytheme
这样简单的语法需要做一些工作,包括创建一个新类来保存主题和zoom 元素,以及覆盖+.gg
方法,我个人认为这不值得麻烦:
make_mytheme <- function(scale, theme) {
structure(list(scale = scale, theme = theme), class = 'mythemeclass')
}
`+.gg` <- function(e1, e2) {
e2name <- deparse(substitute(e2))
if(inherits(e2, 'mythemeclass')) {
e1 <- ggplot2:::add_ggplot(e1, e2$scale, e2name)
return(ggplot2:::add_ggplot(e1, e2$theme, e2name))
} else {
return(ggplot2:::`+.gg`(e1, e2))
}
}
现在,您可以创建一个可以使用的主题,该主题包含zoom 项目和主题项目:
mytheme <- make_mytheme(scale_y_continuous(expand = c(0, 0)),
theme_bw(base_size = 20))
因此,例如,如果我们有以下图:
p <- ggplot(mtcars, aes(gear, mpg)) +
geom_bar(stat = 'summary', fun = mean)
p
我们可以这样做:
p + mytheme
一种更简单的方法是创建一个ggploy本身的包装器:
my_ggplot <- function(...) {
ggplot(...) +
scale_y_continuous(expand = c(0, 0)) +
theme_bw(base_size = 20)
}
这允许:
my_ggplot(mtcars, aes(gear, mpg)) +
geom_bar(stat = 'summary', fun = mean)
可以使用类似的包装器轻松地更改各种几何图形的默认线条粗细,例如:
geom_thickline <- function(...) geom_line(..., size = 2)
或者,再次修改gg添加方法:
thicken_lines <- function(size) {
structure(list(size = size), class = 'thickener')
}
`+.gg` <- function(e1, e2) {
if(inherits(e2, 'thickener')) {
e1$layers <- lapply(e1$layers, function(x) {
x$aes_params <- c(x$aes_params, size = e2$size)
x
})
return(e1)
}
ggplot2:::`+.gg`(e1, e2)
}
这允许:
ggplot(mtcars, aes(gear, mpg)) +
geom_line(stat = 'summary', fun = mean) +
thicken_lines(3)