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

Jul*_*ia 5 plot typography r legend ggplot2

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

plot + theme(legend.text = element_text(face = "italic"))
Run Code Online (Sandbox Code Playgroud)

但我不知道如何仅指定形状图例。我认为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")
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!

Hen*_*rik 6

您可以shape通过element_textscale_shape_discrete* 中设置参数(包括字体)来专门为图例自定义标签。

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")))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


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


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