2

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)

enter image description here

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.

der_grund
  • 1,898
  • 20
  • 36

1 Answers1

2

It is better to prepare the data outside ggplot, see example:

# data prep
plotDat <- rbind(
  data.frame(Group = "Full Data", cars),
  data.frame(Group = "Subset Data", cars[cars$speed < 15, ]))

library(ggplot2)
ggplot(plotDat, aes(x = speed, col = Group, fill = Group)) +
  geom_density(alpha = 0.3)

enter image description here

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    I just realized that this is not an answer for my question since the plot from your suggestion stacks the density plots. Thus, it's a totally different graph. I added `position = "dodge"` to `geom_area` to get the graph I was looking for. Thanks for your idea. – der_grund Jul 25 '16 at 09:35
  • @der_grund correct, used the wrong plot function, see edit. – zx8754 Jul 25 '16 at 09:39