Gọi thư viện

library(ggplot2)
library(ggjoy)
library(RColorBrewer)

Cách 1

Ví dụ với data diamonds

sử dụng lệnh fill đối với cột cần tách nhóm

df <- diamonds

df$cut <- factor(df$cut, levels=names(sort(table(df$cut), de = T)))

ggplot(df, aes(x = price, fill=cut)) + geom_density()+
    scale_fill_manual(values = alpha(rev(brewer.pal(5,"Set1")),.5))+
    theme_bw(base_size = 15)

Ví dụ với data iris

ggplot(iris, aes(x = Sepal.Width, fill=Species)) + geom_density()+
    scale_fill_manual(values = alpha(rev(brewer.pal(5,"Set1")),.5))+
    theme_bw(base_size = 15)

Cách 2

Cách này sử dụng lệnh geom_joy trong gói ggjoy

ggplot(diamonds, aes(x = price, y = cut, fill=cut)) +
    geom_joy(scale = 4) + theme_joy() +
    scale_fill_manual(values = alpha(brewer.pal(5,"Set1"),.7))+
    theme_bw(base_size = 15)

ggplot(iris, aes(x = Sepal.Width, y = Species, fill=Species)) +
    geom_joy(scale = 2) + theme_joy() +
    scale_fill_manual(values = alpha(brewer.pal(5,"Set1"),.7))+
    theme_bw(base_size = 15)