在ggplot中仅对一个图例的标签进行斜体显示 [英] Italicize labels of only one legend in ggplot

查看:298
本文介绍了在ggplot中仅对一个图例的标签进行斜体显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to format a plot with two separate legends on the side. I have a shape legend, for all my different taxa, and a color legend, for the categories they belong in. I want to italicize only the taxon names in the shape legend, and not italicize the category names in the color legend. So far I can make all legend entries italicized or not using this line:

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

但是我不知道如何仅指定形状图例.我认为theme()不适合,因为它会更改整个情节的主题.我也查看了guides(),但似乎没有指定图例标签字体的选项.

But I don't know how to specify the shape legend only. I don't think theme() is appropriate because it changes the theme of the entire plot. I also looked into guides() but it doesn't seem to have an option for specifying font face of the legend labels.

一些样本数据和一个图:

Some sample data and a plot:

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中甚至可能吗?

In sum, I would like to make the species names italicized but not the subfamily names. It seems like it should be simple... Is this even possible in ggplot?

提前谢谢!

推荐答案

您可以通过在scale_shape_discrete *中设置element_text参数(包括字体)来为shape图例专门定制标签.

You can customize labels specifically for the shape legend, by setting element_text parameters, including font, in scale_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")))

*此方法也可用于scale_shape_manual,该参数也具有guide自变量.参见?scale_shape?scale_shape_manual.

*This method also works with scale_shape_manual, which also has a guide argument. See ?scale_shape and ?scale_shape_manual.

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

For some reason I needed to specify angle in element_text, otherwise it errored. You may also need to set size.

这篇关于在ggplot中仅对一个图例的标签进行斜体显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆