如何在ggplot2中的图例中给一个类别斜体化

11

对于我在ggplot2中的图例,我有两个类别,如何只让一个类别变为斜体而另一个不变?

以以下图表为例。我该如何将“Manual”设置为斜体?

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日创建

2个回答

18
你可以使用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日创建的。


3
非常感谢您的回复,r.bot!只想指出,如果您希望将图例条目都向左对齐,您可以添加以下内容:+ theme(legend.text.align = 0)。有关此内容的更多信息,请参见此网址:https://dev59.com/518d5IYBdhLWcg3weiF- - user14353

14

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

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包(v0.3.0)于2020年1月1日创建的。


这个非常好用,非常简单。 - canderson156

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接