Different legend-keys inside same legend in ggplot2
比方说,我不需要\\'proper \\'变量映射,但仍然希望使用图例键来帮助理解图表。我的实际数据类似于以下df
1 2 3 4 5 6 7 | df <- data.frame(id = 1:10, line = rnorm(10), points = rnorm(10)) library(ggplot2) ggplot(df) + geom_line(aes(id, line, colour ="line")) + geom_point(aes(id, points, colour ="points")) |
基本上,我希望相对于
1 2 3 4 5 6 7 | library(reshape2) df <- melt(df, id.vars="id") ggplot() + geom_point(aes(id, value, shape = variable), df[df$variable=="points",]) + geom_line(aes(id, value, colour = variable), df[df$variable=="line",]) |
但是它定义了两个单独的图例。修复第二个代码(并且必须重塑我的数据)也可以,但是我更喜欢一种方法(如果有的话)来手动更改任何图例键(并继续使用第一个方法)。谢谢!
编辑:
感谢@alex,感谢您刷新我有关变量映射的记忆。但是,到目前为止,我最简单的方法仍然是以下操作(非常糟糕的破解!):
1 2 3 4 5 6 | df <- data.frame(id = 1:10, line = rnorm(10), points = rnorm(10)) ggplot(df) + geom_line(aes(id, line, colour ="line")) + geom_point(aes(id, points, shape ="points")) + theme(legend.title=element_blank()) |
只是隐藏了两个不同图例的标题。
欢迎其他想法!!!!
您可以在
1 2 3 4 | ggplot(df) + geom_line(aes(id, line, colour ="line")) + geom_point(aes(id, points, colour ="points"))+ guides(color=guide_legend(override.aes=list(shape=c(NA,16),linetype=c(1,0)))) |
我不知道有什么方法可以轻松地做到这一点,但是您可以这样做(使用融化的数据框)这样的黑客版本:
1 2 3 | p <- ggplot(df.m, aes(id, value)) + geom_line(aes(colour = variable, linetype = variable)) + scale_linetype_manual(values = c(1,0)) + geom_point(aes(colour = variable, alpha = variable)) + scale_alpha_manual(values = c(0,1)) |
关键是您需要正确映射才能使其在图例中正确显示。在这种情况下,获得"正确"的意思是愚弄它,使其看起来像您想要的样子。可能值得指出的是,这只能起作用,因为您可以将