设置文档持久的 ggplot2 颜色主题

ale*_*lex 6 r ggplot2

我想为 Markdown 文档中构建的每个绘图定义一个调色板。本质上,这将覆盖默认选择。

有几个非常古老的答案 - 感谢@dww建议的此处此处的链接- 解决了旧版本的问题(特别是在现代发布了几个主要版本(目前为 3.2.x)时,在 0.8.2 上提出了解决方案) )。

我将说明最接近的用例,设置主题。对于通用主题,这是微不足道的:+ theme_minimal()我可以设置在所有绘图中持续存在的主题,而不是附加在每个绘图上。

library(ggplot2) 

d <- diamonds[sample(1:nrow(diamonds), 1000), ]

## without theming 
ggplot(d, aes(x=carat, y=price, color=clarity)) + 
  geom_point() + 
  theme_minimal() # must set this theme call for every plot 

## setting theme 
theme_set(theme_minimal())

ggplot(d, aes(x=carat, y=price, color=clarity)) + 
  geom_point()    # plot in theme, for all subsequent plots
Run Code Online (Sandbox Code Playgroud)

是否存在类似的修改来设置整个调色板?例如,基于主题的呼叫替换,

ggplot(d, aes(x=carat, y=price, color=clarity)) + 
  geom_point() + 
  scale_color_brewer(palette='Set2') # requesting a global option to set this for all plots
Run Code Online (Sandbox Code Playgroud)

链接的解决方案不依赖于旧版本,而是重载了整个 ggplot 函数。这看起来有风险。

ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer(palette = 'Set1')
Run Code Online (Sandbox Code Playgroud)

All*_*ron 7

有一个ggplot_global环境在内部使用ggplot2但不导出。您可以通过暂时解锁 ggplot 函数的绑定并修改它以将环境内容作为列表返回来查看其结构。您可以像这样非破坏性地执行此操作:

library(ggplot2)

get_ggplot_global <- function()
{
  unlockBinding("theme_set", as.environment("package:ggplot2"))
  backup <- body(theme_set)[[5]]
  body(theme_set)[[5]] <- substitute(return(as.list(ggplot_global)))
  global_list <- theme_set(theme_bw())
  body(theme_set)[[5]] <- backup
  lockBinding("theme_set", as.environment("package:ggplot2"))
  return(global_list)
}

global_list <- get_ggplot_global()
names(global_list)
#> [1] "date_origin"    "element_tree"   "base_to_ggplot" "all_aesthetics"
#> [5] "theme_current"  "time_origin"   
Run Code Online (Sandbox Code Playgroud)

通过检查这个,您可以看到 ggplot 全局环境有一个名为 的对象theme_current,这就是为什么您可以全局设置各种线条、文本和轴元素(包括它们的颜色)。

当您在问题中谈论配色方案时,您指的是在缩放对象中定义的颜色。这不是 ggplot_global 环境的一部分,并且您无法更改默认比例对象,因为没有. 当您创建一个新的 时ggplot(),它有一个用于“scale”的空槽。

因此,您有几个选择:

  1. 将 ggplot 包裹起来my_ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer()
  2. 用上面的函数覆盖 ggplot (按照@Phil的建议)
  3. 创建您自己的主题对象,并使用标准 ggplot 语法添加该对象

最好的办法可能是只写一个 ggplot 的包装器。然而,第三个选项也非常干净和惯用。你可以这样实现:

set_scale <- function(...)
{
  if(!exists("doc_env", where = globalenv()))
    assign("doc_env", new.env(parent = globalenv()), envir = globalenv())
  doc_env$scale <- (ggplot() +  eval(substitute(...)))$scales$scales[[1]]
}

my_scale <- function() if(exists("doc_env", where = globalenv())) return(doc_env$scale)
Run Code Online (Sandbox Code Playgroud)

您可以通过执行以下操作来使用它(例如)

set_scale(scale_color_brewer(palette = "Set2"))

Run Code Online (Sandbox Code Playgroud)

在文档的开头。+ my_scale()所以现在你可以对每个图做:

d <- diamonds[sample(1:nrow(diamonds), 1000), ]

ggplot(d, aes(x=carat, y=price, color=clarity)) +
  geom_point() +
  my_scale()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述