Multi-density plot
Functionality
Plotting multiple density lines for a value which can be subdivided into categories:
Code:
multidensity<-function(dat,idx_col,val_name,fill=T,boarder=F,col_func=rainbow,legend_loc="topleft",from=NULL,to=NULL,...){
library(scales)
val_col<-match(val_name,colnames(dat))
lvls<-sort(unique(dat[,idx_col]))
num_levels<-length(lvls)
cols<- col_func(num_levels)
trans_cols<-alpha(cols,0.3)
ymax<-max(sapply(lvls,function(lvl){max(density(dat[dat[,idx_col]==lvl,val_col],from=0,to=1)$y)}))
if (is.null(from)){from<-min(dat[,val_col])}
if (is.null(to)){to<-max(dat[,val_col])}
if (!("xlim" %in% names(list(...)))){
plot(0,0,type="n",ylim=c(0,ymax),xlim=c(from,to),...)
} else {
plot(0,0,type="n",ylim=c(0,ymax),...)
}
for (lvl in lvls){
d<-density(dat[dat[,idx_col]==lvl,val_col],from=from,to=to)
if (fill==T){ polygon(c(min(d$x),d$x,max(d$x)),c(0,d$y,0),col=trans_cols[match(lvl,lvls)])}
if (boarder==T){ lines(c(d$x,1),c(d$y,0),col=cols[match(lvl,lvls)])}
}
legend(legend_loc,legend=lvls,fill=cols)
}
Usage:
multidensity(x,idx_col,val_name)
Arguments:
Parameter | Description |
---|---|
x | data.frame - data from form which density is computer |
idx_col | String - Name of the column containing the catgories |
val_name | String - Name of column containing numeric values from which density is calculated |
fill | Boolean - Filling of density plot. Default=TRUE |
boarder | Boolean - Plotting of coloured density line. Default=FALSE |
col_func | Function - Name of function used to generate colour palette (e.g. rainbow and terrain.cols) |
legend_loc | String - Position of legend ("topleft","topright","bottomleft","bottomright") |
from | Numeric - Limit density calculation to start from this value |
to | Numeric - Limit density calculation to end at this value |
... | Add more parameters for plotting (e.g. main, xlab,ylab,xlim) |