【问题标题】:How to create a customized theme similar to theme_bw in ggplot2?如何在ggplot2中创建类似于theme_bw的自定义主题?
【发布时间】:2017-06-16 16:38:40
【问题描述】:

我在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 相同但又不会丢失其他选项?

谢谢

【问题讨论】:

  • theme_bw()之后添加自定义主题怎么样?
  • 更改theme 元素的顺序。所以先把主题改成theme_bw,然后再改其他的主题元素。
  • 谢谢各位。是的,它奏效了。很好的解决方案

标签: r ggplot2


【解决方案1】:

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

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

【讨论】:

  • 非常感谢,@A Gore。真是聪明的回答。哇。
  • 您还可以在脚本开头设置此主题并将其应用于所有情节。为此,在进行任何绘图之前,运行theme_set(theme_bw() + theme(...)),其中...theme 函数内的所有代码。然后这个新主题将自动应用于所有后续情节。
  • @eipi 谢谢,是的,它让事情变得更容易
【解决方案2】:

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

`%+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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多