I have two datasets I am trying to display on one chart overlaid in ggplot2 under r. Dataset 1 needs to be displayed as a grouped set of bars (1 group per country - there are a few countries in the dataset). Dataset 2 needs to be displayed as a set of colored horizontal lines across the bars. Note the length of the two datasets differ. I have some code below that illustrates what I am trying to do (designed by advice from others).
library(ggplot2)
chart1_data <- data.frame(year=c("1998","1998","1998","1998","1998","1998","1998","1998","1998"), medicine=c("Fent","Meth","Morph","Fent","Meth","Morph","Fent","Meth","Morph"), entity=c("Italy","Italy","Italy","Norway","Norway","Norway","Portugal","Portugal","Portugal"), usage=c(3.01,9.32,2.01,1.24,1.43,28.48,5.01,5.51,41.82))
chart1_means <- data.frame(label=c("Global Fent","EURO Fent","Global Meth","EURO meth","Global Morph","EURO Morph"), value=c(0.03, 0.07, 1.59, 5.12, 3.28, 8.54))
means_labels = chart1_means$label
colors = rainbow(length(means_labels))
ggplot(data=chart1_data, aes(x=entity, y=usage, fill=medicine)) +
geom_bar(stat="identity", position=position_dodge(), show.legend=TRUE) +
geom_hline(data=chart1_means, aes(yintercept=value), color=colors) +
scale_fill_manual("means", values=colors, guide=guide_legend(override.aes = list(colors)))
The difficulty I'm running into is that I need two legends; one for the bars and one for the lines. All my attempts so far make one legend with pieces of each dataset intermixed to some degree. For example in the chart below notice the single legend with wrong title and nothing about lines.

Does anyone have a recommendation on how I can accomplish what I want? Any pointers appreciated.
As @rawr suggests, things that are mapped use aes() get legends automatically. So do that.
ggplot(data = chart1_data, aes(x = entity, y = usage, fill = medicine)) +
geom_bar(stat = "identity",
position = position_dodge(),
show.legend = TRUE) +
geom_hline(data = chart1_means, aes(yintercept = value, color = label)) +
scale_fill_manual("means",
values = colors) +
scale_color_manual("lines (means?)",
values = colors,
guide = guide_legend(override.aes = list(fill = NA)))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With