I need to plot a variable and a subset of this variable into one graph and I struggle with the placement of the legend. See the following MWE:
library(ggplot2)
ggplot(data = cars, aes(x = speed)) +
geom_line(stat = "density", colour = "red", size = 1) +
geom_area(stat = "density", fill = "red", alpha = 0.3) +
geom_line(data = subset(cars, dist > 50), stat = "density", colour = "blue", size = 1) +
geom_area(data = subset(cars, dist > 50), stat = "density", fill = "blue", alpha = 0.3)
Please note that it is not an option to incluce fill = dist > 50
in the aesthetics for this would split the data into two distinct parts. But the first geom_line
and geom_area
must not only include those values with dist <= 0
, but all values from the data.
Therefore I specify the colors manually in the geom
's. But how can I now add a legend? I would prefer to only include the two geom_line
's.
I tried with scale_color_manual
but did not bring it to work (if this is the way to go, anyway?).
Any suggestions?
EDIT: I changed the code in order to show a working minimal example.