简体   繁体   English

在ggplot2中组合图例

[英]Combine legend in ggplot2

I have a plot of multiple geom_point and a single stat_function in ggplot2 . 我在ggplot2有一个多个geom_point和一个stat_functionggplot2 Is there a way to show a single legend? 有没有办法展示一个传奇?

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)

在此输入图像描述

I want to have a single legend with the blue line and the two colored shapes. 我希望有一个蓝色线条和两个彩色形状的传奇。 I tried 我试过了

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

but this does not work. 但这不起作用。 Is there a way to do this automatically or by hand? 有没有办法自动或手动执行此操作?

Thanks in advance. 提前致谢。

Probably an easier alternative is to use override.aes as follows: 可能更容易的替代方法是使用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"))))

which results in: 这导致:

在此输入图像描述

Specify a . 指定一个. as the shape symbol for your curve and a blank line for your points: 作为曲线的形状符号和点的空白行:

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)

结果情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM