首页 > 解决方案 > ggplot2:如何将标尺的图例与解析的标签相结合?

问题描述

问题

ggplot2中,通常尽可能将不同比例的图例集成到单个组合图例中。到目前为止,这对我来说效果很好。但是,当我尝试解析比例标签以在图例中包含数学符号时,这似乎不起作用。

看这个例子:

# example data
d <- data.frame(x = 1:3, y = rep(0,3), f = c("a[1]", "a[2]", "a[3]"))

# plot
p <- ggplot(data = d, aes(x = x, y = y, color = f, shape = f)) +
  geom_point() +
  guides(
    color = guide_legend(title = "F"),
    shape = guide_legend(title = "F")
  )

下面给出了具有形状/颜色的自定义值以及按预期组合的图例的图。

# plot + custom shapes/colors
p +
  scale_color_manual(name = "F", values = c("red", "blue", "green")) +
  scale_shape_manual(name = "F", values = c(16, 15, 18))

综合传说

但是,在解析标签时,标签按预期出来了,但图例不再合并。

# plot + custom shapes/colors + parsed labels
parse.labels <- function(x) parse(text = x)
p +
  scale_color_manual(name = "F", labels = parse.labels, values = c("red", "blue", "green")) +
  scale_shape_manual(name = "F", labels = parse.labels, values = c(16, 15, 18))

单独的图例

请注意,结果与scale_._discrete而不是相同scale_._manual。同样,为两个比例指定相同的名称guides(shape = guide_legend(title = "F"), color = guide_legend(title = "F"))不会改变这种行为。

问题

如何在维护解析标签的同时整合两个图例?

标签: rggplot2

解决方案


我建议使用labelsin 参数scale_*_discrete()并将您的标签值保存在新向量中的这种方法:

library(ggplot2)
# example data
d <- data.frame(x = 1:3, y = rep(0,3), f = c("a[1]", "a[2]", "a[3]"))
#Labs
lab1 <- c(expression(a[1]),
          expression(a[2]), 
          expression(a[3]))
# plot
ggplot(data = d, aes(x = x, y = y, color = f, shape = f)) +
  geom_point() +
  guides(
    color = guide_legend(title = "F"),
    shape = guide_legend(title = "F")
  )+
  scale_color_discrete(labels = lab1) +
  scale_shape_discrete(labels = lab1)

输出:

在此处输入图像描述


推荐阅读