Thaunes
Thaunes

Reputation: 15

ggplot2 create a geom_hline legend without wasting the barplot one

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.

Upvotes: 1

Views: 1160

Answers (1)

Martin C. Arnold
Martin C. Arnold

Reputation: 9678

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

Upvotes: 5

Related Questions