2016-06-21 52 views
0

我想要生成一个用ggplot2制作的复合图表的好传说,其中有一个闪避的barplot和一个用于显示钡的参考值的水平线泥。问题是,hline图例的特征是“污染”也是barplot的特征。我已经看到类似的主题试图调整提出的其他解决方案,但没有任何显着的结果。ggplot2创建一个geom_hline图例而不浪费barplot一个

这里我举的例子:

数据框:

 Position Year Value 
     Position 1 1999 12 
     Position 2 1999 14 
     Position 3 1999 15 
     Position 1 2000 13 
     Position 2 2000 11 
     Position 3 2000 21 
     Position 1 2001 12 
     Position 2 2001 13 
     Position 3 2001 16 

代码:

ggplot(input, aes(fill=Year , x=Position, y=Value)) + 

    geom_bar(stat="identity", 
    position="dodge", size=0.1, width=0.5, show.legend=TRUE) + 
    labs(title="Barium concentration in the soil") + 
    xlab("Samples") + 
    ylab("Concentration in ng/kg") + 
    scale_y_continuous(limits = c(0, 30)) + 
    #color of barplot 
    scale_fill_manual(values=c("grey40", "grey70", "grey80")) + 

    #limit value 
    geom_hline(aes(yintercept=40, colour = "red"), size=0.9, alpha=0.8, show.legend=TRUE) 

这是图表

chart obtained

正如你可以看到hline传说的功能正在浪费barplot之一。

+0

您需要的AES移出'颜色=“red''从你的' geom_hline'。 – Heroka

+0

通过在'aes'之外移动'color ='red'''命令,你只需从图表中删除hline图例。相反,我想保留它:'geom_hline'图例没问题。问题在于barplot传说被污染了酒吧里的黑色线条bols,这个问题与创建'geom_hline'传说有关。 – Thaunes

+0

[从颜色和填充图例中删除线条可能的重复](http://stackoverflow.com/questions/29941900/remove-lines-from-color-and-fill-legends) – aosmith

回答

3

你可能会做这种方式:

ggplot(input, aes(fill=Year , x=Position, y=Value)) + 
    geom_bar(stat="identity", position="dodge", size=0.1, width=0.5) + 
    labs(title="Barium concentration in the soil") + xlab("Samples") + 
    ylab("Concentration in ng/kg") + 
    scale_y_continuous(limits = c(0, 30))+ 
    geom_hline(aes(yintercept=20, colour="limit"), size=0.9, alpha=0.8) + 
    scale_fill_manual(values=c("grey40", "grey70", "grey80")) + 
    scale_color_manual(name="Foo", values=c(limit="red")) + 
    theme(legend.key = element_rect(fill = "white", colour = "white")) 

然后情节是这样的:

enter image description here

+0

谢谢!完美清晰的解决方案!有没有可能改变传说中红线后面的灰色背景? – Thaunes

+0

不客气。我编辑了我的awnser。该代码现在更具惯用性,图例最后一个条目中的矩形背景现在变成了白色。 –

相关问题