如何在ggplot2中创建类似于theme_bw的自定义主题?

时间:2017-06-16 16:38:41

标签: r ggplot2

我在ggplot2中有以下代码:

require("ggplot2")
df <- data.frame(x=factor(rep(1:2,5)), y=rnorm(10))

ggplot(df , aes(x,y)) + geom_point(size = 3) + 
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
      plot.title = element_text(size=16, face="bold", hjust=0.5)) +
labs(title = "Plot")

现在,我想将背景颜色更改为theme_bw,但主标题和x轴选项将更改回默认值。

ggplot(df , aes(x,y)) + geom_point(size = 3) + 
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
      plot.title = element_text(size=16, face="bold", hjust=0.5)) +
labs(title = "Plot") + 
theme_bw()

那么,如何将主题更改为与theme_bw相同但不丢失其他选项?

由于

2 个答案:

答案 0 :(得分:4)

以下是解决方案(请确保在您要应用的theme_bw()之前使用theme()

ggplot(df , aes(x,y)) + geom_point(size = 3) + 
theme_bw() + 
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
      plot.title = element_text(size=16, face="bold", hjust=0.5)) +
labs(title = "Plot")

答案 1 :(得分:1)

另一个有趣的选择是编写一个只在主题元素尚未定义时才更新主题的函数。因此它类似于+,但主题不能被覆盖,只能添加:

`%+safe%` <- function(e1, e2){
  if (!is.theme(e1) || !is.theme(e2)) {
    stop("%+replace% requires two theme objects", call. = FALSE)
  }

  not_in_e1 <- names(e2)[!names(e2) %in% names(e1)]
  e1[not_in_e1] <- e2[not_in_e1]
  e1
}

ggplot(df , aes(x,y)) + geom_point(size = 3) + labs(title = "Plot") +
  theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
        plot.title = element_text(size=16, face="bold", hjust=0.5))  %+safe% theme_bw()

请注意,这需要使用两个theme个对象,因此您无论如何都必须移动labs()