从颜色中删除线条并填充图例

时间:2015-04-29 11:07:37

标签: r ggplot2

我有一个包含三个不同图例的图:一个用于linetype,一个用于color,另一个用于fill。在colorfill传说中,还有一些我希望删除的行,但是如何删除?

以下是一些示例代码:

# some data
hline_df <- data.frame(name = c('a', 'b'), y = c(1, 2))
df <- data.frame(x = c(1, 2), y = c(0.5, 1.5), con = c('a', 'b'), col = c('d', 'e'))

# the plot
ggplot(df, aes(x, y, fill = con)) +
  geom_bar(stat = 'identity') + 
  geom_point(aes(color = col)) +
  geom_hline(data = hline_df, aes(yintercept = y, linetype = name),
             color = 'red', show_guide = TRUE)

enter image description here

我得到两条红线的“名称”指南,这很好 “col”指南有红线穿过点,我想删除它们!
“con”指南也有红线,应删除。

我可以用

修改图例的部分内容
guides(fill = guide_legend(override.aes = list(colour = NULL)),
       color = guide_legend(override.aes = list(colour = NULL)))

这会删除颜色,但线条仍在那里。

提前致谢!

3 个答案:

答案 0 :(得分:19)

您可以为linetype = 0"blank" linetype设置fillcolor(在不同的guide here})在override.aes来电中。

另请注意,我已将fill aesggplot中的“顶级”移至geom_bar

ggplot(df, aes(x, y)) +
  geom_bar(aes(fill = con), stat = 'identity') + 
  geom_point(aes(color = col)) +
  geom_hline(data = hline_df, aes(yintercept = y, linetype = name), color = 'red', show_guide = TRUE) +
  guides(fill = guide_legend(override.aes = list(linetype = 0)),
         color = guide_legend(override.aes = list(linetype = 0)))

enter image description here

答案 1 :(得分:3)

根据user20650的建议

ggplot(df, aes(x,y)) + 
  geom_hline(data=hline_df,aes(yintercept=y,linetype=name), color='red',show_guide=TRUE) + 
  geom_point(aes(color=col), size=5) + 
  geom_bar(aes(fill=con), stat='identity') + 
  geom_hline(data=hline_df,aes(yintercept=y,linetype=name), color='red',show_guide=F) + 
  guides(color = guide_legend(override.aes = list(linetype = 0)))

所以第一个geom_hline创建了图例,但是线条在栏后面......
第二次调用将线条放在条形图前面,但不打印图例(好主意) 拉斯指南用0覆盖了美学线型...这样就消除了传说中的那条线......我尝试了NULL但是之前没有工作......

再次感谢。

enter image description here

答案 2 :(得分:2)

使用:

ggplot(df, aes(x,y,fill=con)) + geom_bar(stat='identity') + 
  geom_point(aes(color=col)) +
  geom_hline(data=hline_df,aes(yintercept=y,linetype=name),color='red',show_guide=FALSE) +
  guides(linetype=FALSE,color=FALSE)

给了我这个情节: enter image description here

相关问题