2011-09-18 53 views
30

我想創建一個基於theme_bw()ggplot的新主題。複製和修改默認主題

我想象下面的步驟是必須的(在僞代碼):

  1. 製作)theme_bw的副本(:theme_new() <- theme_bw()
  2. 修改副本:如何theme_update(axis.title.x = theme_text(family = base_family, size = base_size, vjust = 0.5))

任何意見實施這個將非常感謝!


編輯: @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() 

Error in match(gparname, names(gpars)) : object 'base_size' not found


編輯: 31/10/2017,@Andrie提供的答案工作得很好。 [R版本3.4.1,ggplot2_2.2.1

回答

10

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))) 
} 
+0

謝謝,這工作!我以前試過,但我沒有弄清楚'base_size = base_size,base_family = base_family'部分,並且總是得到錯誤'匹配錯誤(gparname,names(gpars)):object'base_size'not found'。 – donodarazao

+3

注意:這與ggplot2 0.9中引入的新主題系統現在是多餘的。 – baptiste

+2

[鏈接描述新的主題系統並描述如何修改它。](https://github.com/wch/ggplot2/wiki/New-theme-system) – Gregor

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() 
) 
6

對於新版本的基礎上,文章here

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) 
} 

請注意,我用txttxt_bold避免一遍又一遍寫同樣的東西。

+0

鏈接已損壞。 – zx8754