如何在ggplot2图例中使用下标[R]

问题描述:

我可以在 ggplot2 图例中使用下标吗?我在传说和其他地方的希腊字母上看到了这个问题,但我不知道如何适应它.

Can I use subscripts in ggplot2 legends? I see this question on greek letters in legends and elsewhere, but I can't figure out how to adapt it.

我认为使用适用于轴标签的 expression() 可以解决问题.但是我下面的尝试失败了.谢谢!

I thought that using expression(), which works in axis labels, would do the trick. But my attempt below fails. Thanks!

library(ggplot2)
temp <- data.frame(a = rep(1:4, each = 100), b = rnorm(4 * 100), c = 1 + rnorm(4 * 100))
names(temp)[2:3] <- c("expression(b[1])", "expression(c[1])")
temp.m <- melt(temp, id.vars = "a")
ggplot(temp.m, aes(x = value, linetype = variable)) + geom_density() + facet_wrap(~ a)

以下应该有效(删除带有 names(temp) <-...)的行:

The following should work (remove your line with names(temp) <-...):

ggplot(temp.m, aes(x = value, linetype = variable)) + 
  geom_density() + facet_wrap(~ a) +    
  scale_linetype_discrete(breaks=levels(temp.m$variable),
                          labels=c(expression(b[1]), expression(c[1])))

请参阅 help(scale_linetype_discrete) 以了解可用的自定义(例如通过 name= 的图例标题).

See help(scale_linetype_discrete) for available customization (e.g. legend title via name=).