在一个图中

时间:2016-01-05 16:25:30

标签: r density-plot

我有一个如下所示的数据框:

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

但我想知道是否有一种自动方式可以同时执行所有行,否则这个过程会很快变得很麻烦。

3 个答案:

答案 0 :(得分:8)

您也可以使用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))}
)

enter image description here 如果你想使用颜色,你可以考虑这样的事情:

#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))

enter image description here

答案 1 :(得分:6)

您可以使用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))
}

导致:

enter image description here

答案 2 :(得分:5)

使用stackggplot2

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))

Plot 01

如果密度彼此足够接近并且您需要“尾巴”,您可能会逃脱以下情况:

l <- density(DF$V1)

ggplot(stack(DF)) +
  geom_density(aes(x = values, color = ind)) +
  xlim(range(l$x))

Plot with tails