Home > Enterprise >  Plot several densities with geom_density, but fill using continuous variable
Plot several densities with geom_density, but fill using continuous variable

Time:10-28

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

Thanks in advance!

CodePudding user response:

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)

  • Related