Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plot several densities with geom_density, but fill using continuous variable

I want to plot a grouped density plot using ggplot. Usually, you would use aes(fill = variable_to_group_by) to obtain several densities, each colored/filled by variable_to_group_by.
However, I would like the fill of each density distribution to take the color of a continuous variable (which is unique within each group) instead of the discrete factor that I am using for grouping.

So, I would like to have a distribution per cut as below, but the ‘fill’ color of the distributions should rather be by the continuous variable mean_carat(made below).

diamonds %>%
  group_by(cut) %>% 
  mutate(mean_carat = mean(carat)) %>%
  ungroup() %>%
  ggplot(aes(x = price, fill = cut, color = mean_carat)) +
  geom_density(alpha = 0.3)

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!

>Solution :

Using the group aes you could group by cut but fill by mean_carat:

library(dplyr)
library(ggplot2)

diamonds %>%
  group_by(cut) %>% 
  mutate(mean_carat = mean(carat)) %>%
  ungroup() %>%
  ggplot(aes(x = price, group = cut, fill = mean_carat)) +
  geom_density(alpha = 0.3)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading