2
votes

I'm trying to make a plot that overlays a bunch of simulated density plots that are one color with low alpha and one empirical density plot with high alpha in a new color. This produces a plot that looks about how I want it.

library(ggplot2)
model <- c(1:100)
values <- rnbinom(10000, 1, .4)
df = data.frame(model, values)
empirical_data <- rnbinom(1000, 1, .3)

ggplot() + 
geom_density(aes(x=empirical_data), color='orange') +
geom_line(stat='density', 
          data = df, 
          aes(x=values, 
              group = model),
              color='blue',
          alpha = .05) +
xlab("Value")

However, it doesn't have a legend and I can't figure out how to add a legend to differentiate plots from df and plots from empirical_data.

The other road I started to go down was to put them all in one dataframe but I couldn't figure out how to change the color and alpha for just one of the density plots.

1

1 Answers

3
votes

Moving the color = ... into the aes allows you to call the scale_color_manual and move them into the aes and make the values you pass to color a binding. You can then change it to whatever you want as the actual colors are determined in the scale_color_manual.

ggplot() + 
  geom_density(aes(x=empirical_data, color='a')) +
  geom_line(stat='density', 
            data = df, 
            aes(x=values, 
                group = model,
                color='b'),
            alpha = .05) +
  scale_color_manual(name = 'data source', 
                     values =c('b'='blue','a'='orange'), 
                     labels = c('df','empirical_data')) +
  xlab("Value")