【问题标题】:How to italicize one category in a legend in ggplot2如何在ggplot2的图例中斜体化一个类别
【发布时间】:2018-07-19 04:41:08
【问题描述】:

对于我在 ggplot2 中的图例,我有 2 个类别,如何仅将 1 个类别斜体而不将其他类别斜体?

例如,考虑以下情节。如何设置斜体“手动”?

library(ggplot2)

ggplot(data = mtcars, aes(x = as.factor(am), fill = as.factor(am))) + 
  geom_bar() + 
  scale_fill_discrete(
    "Transmission",
    breaks = c(0, 1),
    labels = c("Automatic", "Manual")
  )

reprex package (v0.3.0) 于 2020-01-01 创建

【问题讨论】:

    标签: r ggplot2 legend italics ggtext


    【解决方案1】:

    您可以使用expressionitalic 在标签上创建斜体文本。

    library(ggplot2)
    
    ggplot(data = mtcars, aes(x = as.factor(am), fill = as.factor(am))) + 
      geom_bar() + 
      scale_fill_discrete(
        "Transmission",
        breaks = c(0, 1),
        labels = c("Automatic", expression(italic("Manual")))
      )
    

    reprex package (v0.3.0) 于 2020-01-01 创建

    【讨论】:

    • 真正有帮助的回复 r.bot,感谢发帖!只是想注意,如果您想让两个图例条目左对齐,您可以添加以下内容:+ theme(legend.text.align = 0)。有关更多信息,请参阅此条目:stackoverflow.com/questions/26781676/…
    【解决方案2】:

    我一直在研究一种更简单、更灵活的方法来实现这个目标,通过 ggtext 包在 ggplot 中启用 markdown 样式。目前正在开发中,但应该很快(2020 年初)发布到 CRAN。

    library(ggplot2) # may require: remotes::install_github("tidyverse/ggplot2")
    library(ggtext)  # remotes::install_github("clauswilke/ggtext")
    
    ggplot(data = mtcars, aes(x = as.factor(am), fill = as.factor(am))) + 
      geom_bar() + 
      scale_fill_discrete(
        "Transmission",
        breaks = c(0, 1),
        labels = c("Automatic", "*Manual*")
      ) +
      theme(legend.text = element_markdown())
    

    reprex package (v0.3.0) 于 2020 年 1 月 1 日创建

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 2017-08-22
      • 1970-01-01
      • 2016-03-27
      • 2018-07-12
      • 2022-10-14
      相关资源
      最近更新 更多