1

I am using ggplot to create two overlapping density from two different data frames. I need to create a legend for each of the densities.

I have been trying to follow these two posts, but still cannot get it to work:

How to add legend to plot with data from multiple data frames

ggplot legends when plot is built from two data frames

Sample code of what I am trying to do:

df1 = data.frame(x=rnorm(1000,0))
df2 = data.frame(y=rnorm(2500,0.5))

ggplot() +
  geom_density(data=df1, aes(x=x), color='darkblue', fill='lightblue', alpha=0.5) + 
  geom_density(data=df2, aes(x=y), color='darkred', fill='indianred1', alpha=0.5) +
  scale_color_manual('Legend Title', limits=c('x', 'y'), values = c('darkblue','darkred')) +
  guides(colour = guide_legend(override.aes = list(pch = c(21, 21), fill = c('darkblue','darkred')))) +
  theme(legend.position = 'bottom')

Is it possible to manually create a legend?

Or do I need to restructure the data as per this post?

Adding legend to ggplot made from multiple data frames with controlled colors

I'm newish to R so hoping to avoid stacking the data into a single dataframe if I can avoid it as they are weighted densities so have to multiply by different weights as well.

1
  • What exactly did you try from those posts? You cannot get a legend for something you haven't mapped in an aes() call. You would need geom_density(data=df1, aes(x=x, color="x"), ...) for your first one and geom_density(data=df2, aes(x=y, color="y"), ...) for your second (since those are the limits you used in the color scale. Commented Aug 9, 2020 at 23:54

1 Answer 1

2

Unlike x, y, label etc., when using the density geom, the color aesthetic can be used within aes(). In order to accomplish what you are looking for, the color aesthetic needs to be moved into aes() enabling you to utilize scale_color_manual. Within that, you can change the values= to whatever you like.

library(tidyverse)
ggplot() +
  geom_density(data=df1, aes(x=x, color='darkblue'), fill='lightblue', alpha=0.5) + 
  geom_density(data=df2, aes(x=y, color='darkred'), fill='indianred1', alpha=0.5) +
  scale_color_manual('Legend Title', limits=c('x', 'y'), values = c('darkblue','darkred')) +
  guides(colour = guide_legend(override.aes = list(pch = c(21, 21), fill = c('darkblue','darkred')))) +
  theme(legend.position = 'bottom')+
  scale_color_manual("Legend title", values = c("blue", "red"))

Created on 2020-08-09 by the reprex package (v0.3.0)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.