Search code examples
rggplot2legenddensity-plot

adding legend to overlaying density plot in ggplot


I have an overlaying density plot from two datasets, created with ggplot2.

  g <- ggplot(data = result_A,
              aes(x = log(cap_universal))) +
    geom_density(fill = "lightblue") +
    geom_density(data = result_B,
                 fill = "purple",
                 alpha = 0.25) +
    xlab("Complete Automation Probability") +
    ylab("Density")

I got what I wanted, a plot looks like this: enter image description here

However, I have tried many ways but still cannot add legends to this plot. There is no error message, but the legend just won't show.

Will appreciate your help.


Solution

  • Combine your data sets result_A and result_B into a single dataset, where the thing these differences are is specified as some factor, e.g. "thing":

    result_A$thing <- "A"
    result_B$thing <- "B"
    result_AB <- rbind(result_A, result_B)
    

    Then instead of calling two datasets with separate calls to geom_density, specify it once with fill = thing and specify your colours and alphas manually, e.g.:

    ggplot(data = result_AB, aes(x = log(cap_universal))) + 
      geom_density(aes(fill = thing,
                       alpha = thing)) +
      scale_fill_manual(values = c("light blue", "purple")) +
      scale_alpha_manual(values = c(1, 0.25)) +
      # assuming here that the "result_A" data will plot first as "A" should
      # order before "B" in factors, though can't test w/out yr data
      xlab("Complete Automation Probability") +
      ylab("Density")
    

    This should produce a legend showing what colour your factors "A" and "B" are, which I assume is what you're after.

    This is more in-line with the philosophy of ggplot2. However it might also work if you wrap both your fill calls inside aes, e.g. geom_density(aes(fill = "lightblue")). (It's impossible to test this though, because you haven't got a reproducible example above)