计算并绘制多个密度?

时间:2020-08-01 18:46:49

标签: r plot

我有一个包含多列的矩阵,我想计算每列的密度,然后在一个R基图中绘制这些密度。如果该图具有自动更正的比例,也会更容易。

m <- matrix(rnorm(10), 5, 10))

2 个答案:

答案 0 :(得分:2)

创建密度d的列表,计算xlimylim的值,并使用这些值创建空图。最后,在该图上绘制每个密度,并可选地绘制图例。根据要求,它仅使用基数R。

set.seed(123)
m <- matrix(rnorm(50), 5, 10) # test data

d <- apply(m, 2, density)

xlim <- range(sapply(d, "[[", "x"))
ylim <- range(sapply(d, "[[", "y"))
plot(NA, xlim = xlim, ylim = ylim, ylab = "density")

nc <- ncol(m)
cols <- rainbow(nc)
for(i in 1:nc) lines(d[[i]], col = cols[i])

legend("topright", legend = 1:nc, lty = 1, col = cols, cex = 0.7)

screenshot

答案 1 :(得分:1)

也可以使用ggplot2

library(reshape2)
library(ggplot2)
#Data
set.seed(123)
m <- as.data.frame(matrix(rnorm(50), 5, 10))
#Melt
meltdata <- melt(m)
#Plot 1
ggplot(meltdata,aes(value,color=variable))+
  geom_density()+ggtitle('Plot 1')
#Plot 2
ggplot(meltdata,aes(value,fill=variable))+
  geom_density(alpha=0.6)+ggtitle('Plot 2')

enter image description here

enter image description here