【问题标题】:How to use subscripts in ggplot2 legends [R]如何在 ggplot2 图例中使用下标 [R]
【发布时间】:2011-09-06 08:33:30
【问题描述】:

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

我认为使用在轴标签中工作的expression() 可以解决问题。但是我在下面的尝试失败了。谢谢!

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)

【问题讨论】:

  • "expression(b[1])" 将被视为字符,而不是表达式。

标签: r ggplot2


【解决方案1】:

以下应该可以工作(用names(temp) &lt;-...删除你的行):

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= 获得图例标题)。

【讨论】:

    【解决方案2】:

    如果您想在主要刻度标签中加入希腊符号等,请使用未评估的expression

    对于条形图,我做了以下操作:

    library(ggplot2)
    data <- data.frame(names=tolower(LETTERS[1:4]),mean_p=runif(4))
    
    p <- ggplot(data,aes(x=names,y=mean_p))
    p <- p + geom_bar(colour="black",fill="white")
    p <- p + xlab("expressions") + scale_y_continuous(expression(paste("Wacky Data")))
    p <- p + scale_x_discrete(labels=c(a=expression(paste(Delta^2)),
                                   b=expression(paste(q^n)),
                                   c=expression(log(z)),
                                   d=expression(paste(omega / (x + 13)^2))))
    p
    

    【讨论】:

    • Error: stat_count() can only have an x or y aesthetic.
    • 有趣的是,这个问题是关于下标的,但你的答案只有上标:(虽然x^2 对我有用,x_2 却不行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2021-01-14
    • 2016-08-05
    • 2021-12-19
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多