将ggplot中只有一个图例的标签设为斜体

Italicize labels of only one legend in ggplot

我正在尝试格式化一个带有两个独立图例的图。我有一个形状图例,用于我所有不同的分类单元,还有一个颜色图例,用于它们所属的类别。我只想将形状图例中的分类单元名称设为斜体,而不将颜色图例中的类别名称设为斜体。到目前为止,我可以使用此行将所有图例条目设为斜体或不设为斜体:

plot + theme(legend.text = element_text(face = "italic"))

但我不知道如何只指定形状图例。我觉得theme()不合适,因为它改变了整个剧情的主题。我也调查了 guides() 但它似乎没有指定图例标签字体的选项。

一些示例数据和绘图:

species <- c("M. mulatta", "P. ursinus", "C. mitis", "C. guereza")
subfam <- c("Cercopithecine", "Cercopithecine", "Cercopithecine", "Colobine")
x <- rnorm(4, 1:10)
y <- rnorm(4, 2:20)
df <- data.frame(cbind(species, subfam, x, y))

ggplot(df, aes(x, y)) + geom_point(aes(shape = species, color = subfam), size = 4) +
  labs(shape = "Species", color = "Subfamily")

总而言之,我想将物种名称设为斜体而不是亚科名称。看起来应该很简单......这在ggplot中甚至可能吗?

提前致谢!

您可以专门为 shape 图例自定义标签,方法是在 scale_shape_discrete*.

中设置 element_text 参数,包括字体
ggplot(df, aes(x, y)) +
  geom_point(aes(shape = species, color = subfam), size = 4) +
  labs(shape = "Species", color = "Subfamily") +
  scale_shape_discrete(guide =
                         guide_legend(label.theme = element_text(angle = 0, face = "italic")))


*此方法也适用于 scale_shape_manual,它也有一个 guide 参数。参见 ?scale_shape?scale_shape_manual


出于某种原因我需要在element_text中指定angle,否则会出错。您可能还需要设置 size.