2013-05-01 75 views
12

比方说,我并不需要一个“适当的”变量映射,但仍希望有传说密钥来帮助图表的理解。我的实际数据是类似于以下DF不同的传说,钥匙,GGPLOT2

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")) 

enter image description here

基本上,我想传说相对于points关键是..只是一个点,没有中间行。我已经接近与此:

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",]) 

但它定义了两个独立的图例。固定第二码(具有重塑我的数据)将被罚款过,但我更喜欢的方式(如果有的话)手动更改任何图例项(并继续使用第一计算策略)。谢谢!

编辑:

感谢您@alexwhan刷新约变量映像我的记忆中。然而,到目前为止,我已经得到了最简单的方法仍然是以下(非常糟糕的劈!):

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()) 

这只是躲藏在两个不同传说的称号。

enter image description here

其他想法多人欢迎!

回答

25

您可以使用override.aes=里面guides()函数来更改图例的默认外观。在这种情况下,你的指导是color=,然后你应该设置shape=c(NA,16)删除形状线,然后linetype=c(1,0)从点删除线。

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)))) 

enter image description here

+0

很不错的方法。可能是最好的一个。我只是想等别人,但它似乎也是唯一一个:-)。无论如何,非常感谢! – Michele 2013-05-16 10:17:35

6

我不知道有什么方法可以很容易地做到这一点,但你可以(使用融化据帧)做一个破解的版本是这样的:

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)) 

enter image description here

的关键是,你需要以获得映射的权利,使其正确显示在图例中。在这种情况下,得到它的“右”,意味着欺骗它寻找你想要的方式。这也许值得指出的是这只能是因为你可以设置linetype空白(0),然后使用alpha规模为点。您不能使用alpha两个,因为只需要一个规模。