在ggplot2中组合图例

时间:2015-10-20 12:18:41

标签: r ggplot2

我在geom_point中有多个stat_function和一个ggplot2的情节。有没有办法展示一个传奇?

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)

enter image description here

我希望有一个蓝色线条和两个彩色形状的传奇。我试过了

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

但这不起作用。有没有办法自动或手动完成?

提前致谢。

2 个答案:

答案 0 :(得分:6)

可能更容易的选择是使用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"))))

导致:

enter image description here

答案 1 :(得分: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