简体   繁体   English

ggplot自定义主题中的条件参数

[英]Conditional argument in ggplot custom theme

I am developing a custom theme based on the 538 theme in ggthemes. 我正在开发基于ggthemes的538主题的自定义主题。 I have a particular use case where I would like to conditionally change the legend text if I am preparing graphs about organisms. 我有一个特殊的用例,如果我准备有关生物的图表,我想有条件地更改图例文本。 I want to make the legend text italics if I am reporting Genus species results. 如果我报告Genus物种结果,我想让传说文本斜体。

Here is my theme so far: 到目前为止,这是我的主题:

theme_EPI <- function() {
  theme_fivethirtyeight(base_size = 14) %+replace%
    theme(
      panel.background  = element_blank(),
      plot.background = element_rect(fill = 'white', colour = NA),
      plot.title = element_text(size = 18),
      strip.text = element_text(size=14),
      legend.text = element_text(size = 12, face = 'italic'),
      legend.background = element_rect(fill="transparent", colour=NA),
      legend.key        = element_rect(fill="transparent", colour=NA),
      panel.grid.major.y = element_line(colour = 'grey90'),
      panel.grid.major.x = element_blank(),
      strip.background = element_blank()
    )
}

If have tried passing the parameter organism=TRUE to the the function call and then an ifelse(organism==TRUE, face='italic', 'face='plain') in the element_text . 如果试图传递参数organism=TRUE的函数调用,然后一个ifelse(organism==TRUE, face='italic', 'face='plain')element_text

Is this even possible in a custom theme? 这在自定义主题中是否可行?

Yes, this is definitely possible, you just have to slightly rethink how the ifelse() will work: 是的,这绝对是可能的,你只需要稍微重新思考ifelse()将如何工作:

theme_EPI = function(organism = TRUE) {
   theme_dark() %+replace%
        # axis.title: labels for x and y axes
        theme(axis.title = element_text(
            face = ifelse(organism, 'italic', 'plain')
        ))
}

ggplot(iris, aes(Petal.Width, Petal.Length)) +
    geom_point() +
    theme_EPI()  # Default: organism = TRUE

ggplot(iris, aes(Petal.Width, Petal.Length)) +
    geom_point() +
    theme_EPI(organism = FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM