0

I want to represent two different 2D distributions using ggplot2. But the two distributions are partially overlapping and I am struggliing to make it look nice.

For example, here is a plot from this code...

    ggplot(control_group, aes(x=eTIV, y=global_SA)) +
      geom_density_2d(bins=4, alpha = .8, color ="blue") +    
      geom_density_2d(data = syn_group, color="red", bins=4, alpha = .8) +
      xlim(1000000, 2000000)+
      ylim(140000, 200000) +
      theme_classic()

enter image description here

I would like the inner contours to be darker and the outer ones to fade out (either with a line or a fill) but can't find anyway of specifying a vector of colours for alpha or fill

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25

1 Answers1

1

You can use the constructed variable after_stat(level) to define the alpha aesthetic. Here's an example with mtcars:

data(mtcars)
library(ggplot2)
  ggplot(mtcars, aes(x=mpg, y=hp, colour=as.factor(am), group=as.factor(am))) +
    geom_density_2d(aes(alpha=after_stat(level)), bins=4, show.legend=TRUE) + 
    scale_alpha_continuous(n.breaks=25) + 
    scale_colour_manual(values=c("red", "blue")) + 
    guides(alpha="none") + 
    labs(colour="Auto/Manual") + 
    theme_classic()

Created on 2023-05-26 with reprex v2.0.2

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25