【问题标题】:ggplot2: how to assign math symbols to legend labels for two different aesthetics?ggplot2:如何将数学符号分配给两种不同美学的图例标签?
【发布时间】:2019-02-07 05:58:05
【问题描述】:

我正在尝试用数学符号制作一个图例。我尝试了不同的选项,但没有一个有效。我找不到将标签直接分配给guide_legend 的方法,而 ggplot 似乎无法理解因子级别的expressions。将label_bquote 分配给因子级别也会失败(无论如何,ggplot2 文档说它适用于分面条)。

在下面的示例中,我想将 L1、L2 和 Linf 分别更改为带有下标 1、2 和无穷大符号的 L。

a1 = exp(seq(1, 3))
a2 = exp(seq(1, 3) + 0.2)
a3 = exp(seq(1, 3) + 0.4)

df = data.frame(coefficients = c(a1, a2, a3), order = rep(1:3, 3),
                norm = factor(rep(1:3, each = 3), labels =  expression(L[1], L[2], L[inf])))

ggplot(df, aes(x = order, y = coefficients, colour = norm, shape = norm)) + 
geom_line() + geom_point() 

【问题讨论】:

  • 我投票决定重新打开,因为这个传说是针对 两种 美学而另一个问题仅针对一种美学。这里必须使用scale_color_manual(values=c("red", "blue", "green"), labels=labels) + scale_shape_manual(values=c(1,2,3), labels=labels) 和@987654328 做类似的事情@.
  • @StéphaneLaurent 将链接帖子的解决方案适应多种美学似乎非常简单(即微不足道)。我真的不明白这有什么显着不同。但如果有更多支持重新开放电话,我很高兴重新开放。
  • @MauritsEvers 对我来说这并不简单。我必须搜索一段时间才能找到这个解决方案(因为我也有一段时间没有使用 ggplot )。如果问题被重新打开,则应在标题中提及这一差异。
  • @MauritsEvers 原始问题中的答案有效,但正如 Stéphane 指出的那样,需要明确地将标签分配给两种尺度。如果我更改标题而您重新打开问题怎么办?
  • @MarcoStamazza 完成

标签: r ggplot2 legend symbols


【解决方案1】:

我忽略了 similar question 已经被问及答案给出了正确的提示:通过比例分配标签,如下所示。请注意,必须定义两个比例,并且两者必须具有相同的名称和标签,以避免产生两个图例。

a1 = exp(seq(1, 3))
a2 = exp(seq(1, 3) + 0.2)
a3 = exp(seq(1, 3) + 0.4)

df = data.frame(coefficients = c(a1, a2, a3), order = rep(1:3, 3),
                  norm = factor(rep(1:3, each = 3), labels = c("L1", "L2", "Linf")))

ggplot(df, aes(x = order, y = coefficients, colour = norm, shape = norm)) + 
  geom_line() + geom_point() + 
scale_colour_manual(name = "norm", values = c("blue", "red", "green"), 
                     labels = expression(L[1], L[2], L[infinity])) + 
scale_shape_discrete(name = "norm", 
                      labels = expression(L[1], L[2], L[infinity]))

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多