1
votes

I'm trying to generate a good legend for a composite chart made with ggplot2, where there is a dodged barplot and an horizontal line used for showing a reference value of barium in the soil. The problem is that the features of the hline legend are "polluting" also the barplot one. I've already seen similar topics trying to adjust other solution proposed but without any significant results.

Here my example:

Dataframe:

       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

The code:

    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 )

And this is the chart

chart obtained

As you can see the features of the hline legend are wasting the barplot one.

1
You need to move colour="red' outside the aes from your geom_hline. - Heroka
By Moving the 'colour="red'" ' command outside of 'aes' , you simply delete the hline legend from the chart. At the contrary I want to keep it: the 'geom_hline' legend is ok. The problem is that the barplot legend is polluted with that black lines inside the bar simbols and this problem is related to the creation of the 'geom_hline' legend. - Thaunes
The way your data is represented you cannot use it with your code. For instance the year variable must be formated as character, otherwise it will not work. I recommend using dput(your_data.frame) and add this to your question. - Alex

1 Answers

5
votes

You might do it this way:

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

The plot then looks like this:

enter image description here