复制和修改默认主题

时间:2011-09-18 06:10:12

标签: r themes plot ggplot2

我想基于ggplottheme_bw()创建一个新主题。

我想以下步骤是必要的(伪代码):

  1. 制作theme_bw()的副本:theme_new() <- theme_bw()
  2. 修改副本:theme_update(axis.title.x = theme_text(family = base_family, size = base_size, vjust = 0.5))
  3. 非常感谢任何关于如何实现这一点的建议!


    编辑: @Andrie,我根据自己的需要修改了答案:

    theme_new <- theme_set(theme_bw())
    theme_new <- theme_update(axis.title.x = theme_text(family = base_family, size = base_size, vjust = 0.5))
    

    但是,我收到以下错误:

    ggplot(mtcars, aes(factor(cyl))) + geom_bar()
    
      

    匹配错误(gparname,names(gpars)):找不到对象'base_size'


    编辑: 2017年10月31日,@ Andrie提供的答案工作得很好。 R版本3.4.1,ggplot2_2.2.1

4 个答案:

答案 0 :(得分:25)

您的代码只需要进行一些小的更改(主要是删除括号并在正确的位置添加括号)

theme_new <- theme_set(theme_bw())

theme_new <- theme_update(
    panel.background = element_rect(fill="lightblue"))

ggplot(mtcars, aes(factor(cyl))) + geom_bar()

enter image description here


参考:

答案 1 :(得分:11)

wiki建议使用modifyList

执行此操作的一种方法
theme_new <- function (base_size = 12, base_family = "", ...){
 modifyList (theme_bw (base_size = base_size, base_family = base_family),
          list (axis.title.x = theme_text(family = base_family, 
                size = base_size, vjust = 0.5)))
}

答案 2 :(得分:6)

对于较新版本,基于文章here

$(".searchEl")

请注意,我使用txt <- element_text(size = 14, colour = "black", face = "plain") bold_txt <- element_text(size = 14, colour = "black", face = "bold") theme_whatever <- function(base_size = 14, base_family = "Palatino") { theme_bw(base_size = base_size, base_family = base_family) + theme( legend.key = element_blank(), strip.background = element_blank(), text = txt, plot.title = txt, axis.title = txt, axis.text = txt, legend.title = bold_txt, legend.text = txt ) } txt来避免一遍又一遍地写同样的内容。

答案 3 :(得分:5)

尝试这样:

### Set up a blank theme
theme_none <- theme(
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),
  panel.background = element_blank(),
  axis.title.x = element_text(colour=NA),
  axis.title.y = element_blank(),
  axis.text.x = element_blank(),
  axis.text.y = element_blank(),
  axis.line = element_blank()
  #axis.ticks.length = element_blank()
)