Skip to content

Instantly share code, notes, and snippets.

@ottadini
Last active December 25, 2015 17:49
Show Gist options
  • Save ottadini/7016362 to your computer and use it in GitHub Desktop.
Save ottadini/7016362 to your computer and use it in GitHub Desktop.
Plot multiple density curves on one graph in R base graphics, taking care of the axis limits.

plot.multi.dens <- function(s){
# From: http://onertipaday.blogspot.com.au/2007/09/plotting-two-or-more-overlapping.html
# the input s MUST be a numeric list
# e.g.
# rating <- rnorm(200)
# rating2 <- rnorm(200, mean=.8)
# plot.multi.dens( list(rating, rating2))
junk.x = NULL
junk.y = NULL
for(i in 1:length(s)) {
junk.x = c(junk.x, density(s[[i]])$x)
junk.y = c(junk.y, density(s[[i]])$y)
}
xr <- range(junk.x)
yr <- range(junk.y)
plot(density(s[[1]]), xlim = xr, ylim = yr, main = "")
for(i in 1:length(s)) {
lines(density(s[[i]]), xlim = xr, ylim = yr, col = i)
}
}
## ggplot2 version would be something like:
#library(ggplot2)
#qplot(V1, colour=factor(V2), data=mydataframe, geom="density")
## requires data to be in 'wide' format - use reshape2 library (melt etc)
## Or:
#vec1 <- data.frame(x=rnorm(2000, 0, 1))
#vec2 <- data.frame(x=rnorm(3000, 1, 1.5))
#ggplot() + geom_density(aes(x=x), colour="red", data=vec1) +
# geom_density(aes(x=x), colour="blue", data=vec2)
## Another version from http://stackoverflow.com/a/12456601/857416
ranges <- apply(mydataframe, 2,
function(x) { dens <- density(x); c(range(dens$x), range(dens$y)) })
plot(density(mydataframe$samp1), col="red",
xlim = range(ranges[1:2, ]), ylim = range(ranges[3:4, ]))
lines(density(mydataframe$samp2), col="green")
lines(density(mydataframe$samp3), col="blue")
## Or alternative plot routine:
ranges <- apply(mydataframe, 2,
function(x) { dens <- density(x); c(range(dens$x), range(dens$y)) })
plot(0, type = "n", xlim = range(ranges[1:2, ]), ylim = range(ranges[3:4, ])) # empty plot
COL = rainbow(ncol(mydataframe))
lapply(1:(ncol(mydataframe)), function(x) lines(density(mydataframe[, x]), col = COL[x]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment