开发者

Copying and modifying a default theme

开发者 https://www.devze.com 2023-04-05 10:25 出处:网络
I would like to create a new theme for ggplot that is based on theme_bw(). I imagine the following steps are necessary (in pseudocode):

I would like to create a new theme for ggplot that is based on theme_bw().

I imagine the following steps are necessary (in pseudocode):

  1. Make a copy of theme_bw(): theme_new() <- theme_bw()
  2. Modify the copy: theme_update(axis.title.x = theme_text(family = base_family, size = base_size, vjust = 0.5))

Any advice on how to implement this will be very much appreciated!


Edit: @Andrie, I modified your answer for my needs:

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

However, I get the following error:

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

Error in match(gparname, names(gpars)) : object 'base_siz开发者_StackOverflow中文版e' not found


Edit: 31/10/2017, answer provided by @Andrie works just fine. R version 3.4.1, ggplot2_2.2.1


Your code just needs a few small changes to work (mainly removing brackets and adding brackets at the right places)

theme_new <- theme_set(theme_bw())

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

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

Copying and modifying a default theme


Reference:

  • CRAN: extending-ggplot2
  • Tidyverse: themes
  • GitHub: New-theme-system


the wiki suggests one way to do this using 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)))
}


For the newer versions, based on the article 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 ) 
}

Note that I use txt and txt_bold to avoid writing same stuff over and over again.


Try like this one:

### 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()
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号