0

I would like to represent my data (PCA) as two (even more) overlapping 2D density regions, colored by a specific factor. For each factor value, the most 'densely populated' area should be also darker than less populated regions. I used stat_density_2d():

ggplot(mydf, aes(PC1, PC2,colour=as.factor(class))) +
  stat_density_2d()

getting this plot: PCA with contours

Then, I tried different combination of stat_density_2d(aes()) arguments, such as fill=, but unsuccessfully.

  • Hi Mattia, it would be best to add a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) in your question. you can achieve this by doing `dput(mydf)` – Bushidov Sep 15 '22 at 07:06
  • Thanks @Bushidov for the comment. I provide you with an example code, using the `iris` dataset: `library(ggplot2) data("iris") pc <- prcomp(iris[,-5], center = TRUE, scale. = TRUE) mydf <- cbind(pc$x,iris[,5,drop=F]) ggplot(mydf, aes(PC1, PC2,colour=Species)) + stat_density_2d()` – Mattia_C Sep 15 '22 at 10:01

0 Answers0