I would like to create a plot with multiple geoms (e.g. geom_line and geom_bar) using both fill and colour, but with just one single, consolidated guide, rather than one guide for fill and another for colour.
To complicate matters, this is part of an application that lets the user upload data, so I don't know the names of each series, or even how many there will be. So the guides need to be automatically generated.
The examples that I have seen all use scale_colour_manual
and scale_colour_fill
but this assumes that you know the name of the series. For example: ggplot2 merge color and fill legends
I've tried to look into the structure of the finished plot, to see if I can manually extract the series names (and their colours, etc...), but can't see that anywhere.
Here's some test data. I'm using the "group" column to decide if it should be in the line or bar geoms.
testdt <- data.table(
x = rep(c(1,2), each = 4),
name = c("a", "b", "c", "d"),
value = c(1,2,3,4,5,6,7,8),
group = c(1,2)
)
ggplot(data = testdt, aes(x = x, y = value)) +
geom_line(data = testdt[group == 1], aes(colour = name)) +
geom_bar(data = testdt[group == 2], aes(fill = name), stat = "identity")
This example yields two legends; both are called "name", one shows the "a" and "c" lines and the other shows the "b" and "d" areas.
Edit - clarifying what it should look like
Here's a before image:
And this is what I would like it to look like: