整合ggplot2中的图例

7

我有一个包含多个geom_point和单个stat_function的图形,有没有办法只显示一个图例?

df <- data.frame("x"=c(1:5), "a"=c(1,2,3,3,3), "b"=c(1,1.1,1.3,1.5,1.5))
df <- melt(df, "x")
p <- ggplot(df, aes(x=x, y=value)) +
  geom_point(aes(colour=variable, shape=variable)) +
  stat_function(aes(colour="log2(x)"), fun=log2)

这里输入图片描述

我希望在图例中同时显示蓝线和两个彩色形状。我尝试过,但未能成功。

scale_colour_discrete(name="legend", breaks=c("a", "b", "log2(x)")) +
scale_shape_discrete(name="legend", breaks=c("a", "b"))

但这种方法不起作用。有没有自动或手动的方法可以做到这一点?
提前致谢。
2个回答

7

也许更简单的替代方案是使用override.aes,如下所示:

ggplot(df, aes(x = x, y = value)) +
  geom_point(aes(colour = variable, shape = variable), size = 3) +
  stat_function(aes(colour = "log2(x)"), fun = log2, size = 1.5) +
  guides(shape = FALSE,
         colour = guide_legend(override.aes = list(shape = c(16, 17, NA),
                                                   linetype = c("blank", "blank", "solid"))))

这将导致:

输入图像描述


4

对于曲线形状符号,请指定为.,对于点请使用空行:

p <- ggplot(df, aes(x=x, y=value)) +
  geom_point(aes(colour=variable, shape=variable, linetype = variable), size = 3) +
  stat_function(aes(colour="log2(x)", shape = "log2(x)", linetype = "log2(x)"), fun=log2) +
  scale_shape_manual(values = setNames(c(16, 17, 46), c("a", "b", "log2(x)"))) +
  scale_linetype_manual(values = setNames(c(0, 0, 1), c("a", "b", "log2(x)")))
print(p)

resulting plot


谢谢,这个可行。但我认为@Jaap的答案是更“官方”的方式。 - dbrettschneider
当然,如果你能记得它,而我却不能。 - Roland
1
我建议使用这个选项,而不是目前被接受的答案。覆盖指南存在人为错误的风险,导致标记值不准确的指南。然而,使用这个答案,即使在比例规范中出现错误,指南也将始终准确。 - W. Murphy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接