我有一个如下所示的数据框:
DF<-as.data.frame(t(replicate(150, sample(seq(100, 1000),15,replace=T))),rownames=T)
我想将各行绘制为密度,以便得到具有多个密度曲线的图.我知道我可以一行一行地做到这一点:
plot(density(DF[,1]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,2]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,3]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,4]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,5]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,6]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,7]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,8]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,9]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,10]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,11]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,12]),col = adjustcolor('black', alpha.f = .5)) lines(density(DF[,13]),col = adjustcolor('black', alpha.f = .5)) #...and so forth
但我想知道是否有一种自动方式一次完成所有行,否则这个过程会很快变得麻烦.
你也可以使用lapply:
plot(density(DF[,1]),col = adjustcolor('black', alpha.f = .5),ylim=c(0,0.0015)) lapply(DF[,-1],function(x){lines(density(x),col = adjustcolor('black', alpha.f = .5))} )
如果你想使用颜色,你可以考虑这样的事情:
#making a palette mycols <- rainbow(ncol(DF)) #plotting, now using numerical column indices to access colour at same time plot(density(DF[,1]),col = adjustcolor(mycols[1], alpha.f = .5),ylim=c(0,0.0015)) lapply(2:ncol(DF),function(x){lines(density(DF[,x]),col = adjustcolor(mycols[x], alpha.f = .5))} ) #add legend legend(x=1100, y=0.0015,col=mycols,lty=1,legend=colnames(DF))
你可以使用for
循环.
DF<-as.data.frame(t(replicate(150, sample(seq(100, 1000),15,replace=T))),rownames=T) plot(density(DF[,1]),col = adjustcolor('black', alpha.f = .5)) for (i in 2:ncol(DF)){ lines(density(DF[, i]), col = adjustcolor('black', alpha.f = 0.5)) }
这导致:
使用stack
和ggplot2
:
library(ggplot2) head(stack(DF)) # values ind # 1 763 V1 # 2 833 V1 # 3 620 V1 # 4 819 V1 # 5 148 V1 # 6 549 V1 ggplot(stack(DF)) + geom_density(aes(x = values, color = ind))
如果密度彼此足够接近并且您需要"尾巴",则可以通过以下方式逃脱:
l <- density(DF$V1) ggplot(stack(DF)) + geom_density(aes(x = values, color = ind)) + xlim(range(l$x))