Speak a “list” of densities

I have a data.frame consisting of 10 columns and 50 rows. I computed the density function, column by column, using the apply function. Now I would like to calculate the densities that I calculated immediately.

In other words, instead of plotting ...

plot(den[[1]]) plot(den[[2]] plot(den[[3]] 

... I would like to immediately display all the densities.

I suppose I need to use the lapply function, and probably I need to write a specific function for this. Can anybody help me?

+4
source share
3 answers

latticeExtra has a very convenient function, marginalplot

 marginal.plot(DF,layout=c(2,2)) 

enter image description here

+1
source

Maybe that would be helpful

 set.seed(001) DF <- data.frame(matrix(rnorm(400, 100, 12), ncol=4)) # some data den<-apply(DF, 2, density) # estimating density par(mfrow=c(2,2)) sapply(den, plot) # plot each density par(mfrow=c(1,1)) 

What gives...

enter image description here

Providing some names:

 par(mfrow=c(2,2)) for(i in 1:length(den)){ plot(den[[i]], main=paste('density ', i)) } par(mfrow=c(1,1)) 

enter image description here

If you just don’t want all the graphs to be on the same output, you can exit par(mfrow=c(2,2)) and just run sapply(den, plot)

Edit: answer the second question (in the comment)

 plot(den[[1]], ylim=c(0,.04), main='Densities altogether') # plot the first density for(i in 2:length(den)){ # Add the lines to the existing plot lines(den[[i]], col=i) } 

enter image description here

It’s useful to use the legend function to add a legend.

 legend('topright', paste('density ', 1:4), col=1:4, lty=1, cex=.65) 
+6
source

I think a lattice package might be convenient:

The following example is from Jilber:

 set.seed(001) DF <- data.frame(matrix(rnorm(400, 100, 12), ncol=4)) # some data DF <- stack(DF) # to long form library(lattice) densityplot(~values|ind, DF, as.table=TRUE) # or densityplot(~values, groups=ind, DF) 

Results:

Separate densities

and

Combined densities

+1
source

Source: https://habr.com/ru/post/1444759/


All Articles