Reputation: 1141
I have a data.frame composed of 10 columns and 50 rows. I computed density function, column by column using the apply function. Now I would like to plot the densities I computed at once.
In other words, instead of plotting...
plot(den[[1]])
plot(den[[2]]
plot(den[[3]]
...I would like to plot all the densities at once.
I suppose I have to use the lapply
function and probably I have to write a specific function to do this. Can anyone help me?
Upvotes: 6
Views: 1392
Reputation: 121568
latticeExtra
has very handy function, marginalplot
marginal.plot(DF,layout=c(2,2))
Upvotes: 1
Reputation: 50704
I think that lattice
package could be handy:
Following example 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 are:
and
Upvotes: 1
Reputation: 61154
Maybe this 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))
Which gives...
Giving 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))
If you just don't want all plots in one output you may want to leave par(mfrow=c(2,2))
out and just run sapply(den, plot)
Edit: Answer for your 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)
}
Here is useful using legend
function to add a legend
legend('topright', paste('density ', 1:4), col=1:4, lty=1, cex=.65)
Upvotes: 7