为所有情节设置主题和调色板

Mar*_*nes 6 r ggplot2

我正在尝试简化我在ggplot2. 假设我想从 iris 数据集创建一个散点图:

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point()
Run Code Online (Sandbox Code Playgroud)

虹膜散点图

但假设我不喜欢ggplot2默认主题和调色板。假设我想使用theme_bwDark2调色板:

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  theme_bw() +
  scale_color_brewer(palette="Dark2")
Run Code Online (Sandbox Code Playgroud)

带有另一个调色板的虹膜散点图

假设我有很多图,我希望所有图都使用theme_bwDark2调色板。我知道我可以theme_set(theme_bw())用来使我的所有情节都具有黑白主题。是否有类似的功能可以让我的所有图都使用Dark2调色板?换句话说,我怎样才能运行像

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point()
Run Code Online (Sandbox Code Playgroud)

并有theme_bwDark2调色板在我所有的情节?

LAP*_*LAP 4

一种解决方案是编写自定义包装器:

ggcust <- function(...){
  ggplot(...) +
    theme_bw()
}
Run Code Online (Sandbox Code Playgroud)

填写theme您需要的所有选项,然后像这样使用它:

ggcust(data = mtcars, aes(x = mpg, y = cyl)) +
  geom_point()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述