如何为ggplot2全局设置主题? [英] How to set themes globally for ggplot2?

查看:191
本文介绍了如何为ggplot2全局设置主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有很多功能的程序包,这些程序可以生成ggplot图.

I created a package with plenty of functions that generate ggplot plots.

一开始,我对所有绘图功能都使用了默认主题(灰色主题),但后来发现黑白主题对眼睛来说更令人愉悦,并使用该主题开发了最新的绘图功能.

At the beginning, I used the default theme for all my plot functions (grey theme) but then I found the black and white theme to be more pleasant to the eye and developed my latest plot functions using that theme.

有没有一种方法可以全局设置ggplot2主题,即在一个地方,而不必每次发现新主题都需要修改所有绘图功能时才将其应用于所有绘图?

Is there a way to set the ggplot2 theme globally, i.e. in one place, without having to modify all my plot functions each time I find a new theme I want to apply to all my plots?

推荐答案

我要做的是设置

th <- theme()

,然后将其包含在所有ggplots中.需要在任何特定于绘图的主题之前添加它,否则它将覆盖它们.

at the top of my script and then include this to all ggplots. It needs to be added before any plot specific themes or it will overwrite them.

df <- data.frame(x = rnorm(100))
ggplot(df, aes(x = x)) +
  geom_histogram() + 
  th +
  theme(panel.grid.major = element_line(colour = "pink"))

稍后,您可以将th更改为其他主题

At a later stage, you can then change th to a different theme

theme_set以及相关功能theme_replacetheme_update可能是此问题的更好解决方案.他们不需要编辑现有代码.

theme_set and related functions theme_replace and theme_update suggested by hrbrmstr in the comments are probably better solutions to this problem. They don't require existing code to be edited.

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

这篇关于如何为ggplot2全局设置主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆