ggplot 中多个组的密度图

sym*_*ymo 3 r ggplot2 density-plot plotly

我看过example1如何在 R 中叠加密度图?ggplot2 中关于如何制作密度图的重叠密度图。我可以使用第二个链接中的代码制作密度图。但是我想知道如何在ggplot或 中制作这样的图表plotly?我已经查看了所有示例,但无法解决我的问题。我有一个带有基因表达白血病数据描述的玩具数据框,其中的哪些列指的是两组个体

leukemia_big <- read.csv("http://web.stanford.edu/~hastie/CASI_files/DATA/leukemia_big.csv")

df <- data.frame(class= ifelse(grepl("^ALL", colnames(leukemia_big),
                 fixed = FALSE), "ALL", "AML"), row.names = colnames(leukemia_big))

plot(density(as.matrix(leukemia_big[,df$class=="ALL"])), 
     lwd=2, col="red")
lines(density(as.matrix(leukemia_big[,df$class=="AML"])), 
      lwd=2, col="darkgreen")
Run Code Online (Sandbox Code Playgroud)

Nic*_*uez 6

Ggplot 需要整齐的格式化数据,也称为长格式数据帧。下面的例子将做到这一点。但请注意,提供的数据集具有几乎相同的患者类型分布值,因此当您绘制 ALL 和 AML 类型的患者时,曲线重叠,您看不到差异。

library(tidyverse)

leukemia_big %>% 
as_data_frame() %>% # Optional, makes df a tibble, which makes debugging easier
gather(key = patient, value = value, 1:72) %>% #transforms a wide df into a tidy or long df
mutate(type = gsub('[.].*$','', patient)) %>% #creates a variable with the type of patient
ggplot(aes(x = value, fill = type)) + geom_density(alpha = 0.5)
Run Code Online (Sandbox Code Playgroud)

结果与原始数据

在第二个示例中,我将为所有 AML 类型的患者的 value 变量添加 1 个单位,以直观地展示重叠问题

leukemia_big %>% 
as_data_frame() %>% # Optional, makes df a tibble, which makes debugging easier
gather(key = patient, value = value, 1:72) %>% #transforms a wide df into a tidy or long df
mutate(type = gsub('[.].*$','', patient)) %>% #creates a variable with the type of patient
mutate(value2 = if_else(condition = type == "ALL", true = value, false = value + 1)) %>% # Helps demonstrate the overlapping between both type of patients
ggplot(aes(x = value2, fill = type)) + geom_density(alpha = 0.5)`
Run Code Online (Sandbox Code Playgroud)

AML 类型患者修改数据的结果