Search code examples
rplyrkernel-density

Densityplots using colwise - different colors for each line?


I need a plot of different density lines, each in another color. This is an example code (but much smaller), using the built-in data.fame USArrests. I hope it is ok to use it?

colors <- heat.colors(3)  
plot(density(USArrests[,2], bw=1, kernel="epanechnikov", na.rm=TRUE),col=colors[1])     
lines1E <- function(x)lines(density(x,bw=1,kernel="epanechnikov",na.rm=TRUE))    
lines1EUSA <- colwise(lines1E)(USArrests[,3:4])`  

Currently the code produces with colwise() just one color. How can I get each line with another color? Or is there ab better way to plot several density lines with different colors?


Solution

  • I don't quite follow your example, so I've created my own example data set. First, create a matrix with three columns:

    m = matrix(rnorm(60), ncol=3)
    

    Then plot the density of the first column:

    plot(density(m[,1]), col=2)
    

    Using your lines1E function as a template:

    lines1E = function(x) {lines(density(x))}
    

    We can add multiple curves to the plot:

    colwise(lines1E)(as.data.frame(m[ ,2:3]))
    

    Personally, I would just use:

    ##Added in NA for illustration
    m = matrix(rnorm(60), ncol=3)
    m[1,] = NA
    plot(density(m[,1], na.rm=T))
    sapply(2:ncol(m), function(i) lines(density(m[,i], na.rm=T), col=i))
    

    to get:

    enter image description here