我创建了一个包含大量函数的包,可以生成ggplot图.
一开始,我使用了所有情节功能(灰色主题)的默认主题,但后来我发现黑白主题更加令人愉悦,并使用该主题开发了我最新的情节功能.
有没有办法全局设置ggplot2主题,即在一个地方,而不必在每次找到我想要应用于我所有情节的新主题时修改我的所有绘图功能?
小智 45
在这里,你应该再次附上包裹
library(ggplot2); theme_set(theme_bw())
Run Code Online (Sandbox Code Playgroud)
Ric*_*ord 11
我所做的就是设定
th <- theme()
Run Code Online (Sandbox Code Playgroud)
在我的脚本的顶部,然后将其包含在所有ggplots中.它需要在任何绘图特定主题之前添加,否则它将覆盖它们.
df <- data.frame(x = rnorm(100))
ggplot(df, aes(x = x)) +
geom_histogram() +
th +
theme(panel.grid.major = element_line(colour = "pink"))
Run Code Online (Sandbox Code Playgroud)
稍后,您可以更改th为其他主题
theme_set和相关的功能theme_replace以及theme_updatehrbrmstr在评论中建议的可能是解决这个问题的更好方法.它们不需要编辑现有代码.
g <- ggplot(df, aes(x = x)) +
geom_histogram() +
g
old <- theme_set(theme_bw()) #capture current theme
g
theme_set(old) #reset theme to previous
Run Code Online (Sandbox Code Playgroud)
现在有一个 R 包来全局设置主题。https://rstudio.github.io/thematic/
他们的示例代码:
图书馆(专题)
主题开(
bg = "#222222", fg = "white", 口音 = "#0CE3AC",
font = font_spec("Oxanium", scale = 1.25)
)
之后,每个图都会继承这些设置。