Path: blob/master/sandbox/paper_analysis/R_interpretation/chart.StackedBar.R
1433 views
chart.StackedBar2 =1function (w, colorset = NULL, space = 0.2, cex.legend = 0.8,2cex.names = 1, cex.axis = 1, las = 3, legend.loc = "under",3element.color = "black", unstacked = TRUE, xlab = NULL,4ylim = NULL, axisnames = TRUE , l=1.9, r=1, u = 4, ...)5{6w = checkData(w, method = "matrix")7w.columns = ncol(w)8w.rows = nrow(w)9if (is.null(colorset))10colorset = 1:w.columns11if (is.null(xlab))12minmargin = 313else minmargin = 514if (unstacked & dim(w)[1] == 1) {15if (las > 1) {16bottommargin = max(c(minmargin, (strwidth(colnames(w),17units = "in"))/par("cin")[1])) * cex.names18par(mar = c(bottommargin, l, u, r) + 0.1)19}20barplot(w, col = colorset[1], las = las, horiz = FALSE,21space = space, xlab = xlab, cex.names = cex.names,22axes = FALSE, ylim = ylim, ...)23axis(2, col = element.color, las = las)24}25else {26op <- par(no.readonly = TRUE)27if (!is.null(legend.loc)) {28if (legend.loc == "under") {29layout(rbind(1, 2), height = c(6, 1), width = 1)30}31else par(mar = c(5, l, u, r) + 0.1)32}33if (las > 1) {34bottommargin = max(c(minmargin, (strwidth(rownames(w),35units = "in"))/par("cin")[1])) * cex.names36par(mar = c(bottommargin, l, 4, r) + 0.1)37}38else {39if (is.null(xlab))40bottommargin = 341else bottommargin = 542par(mar = c(bottommargin, l, u, r) + 0.1)43}44positives = w45for (column in 1:ncol(w)) {46for (row in 1:nrow(w)) {47positives[row, column] = max(0, w[row, column])48}49}50negatives = w51for (column in 1:ncol(w)) {52for (row in 1:nrow(w)) {53negatives[row, column] = min(0, w[row, column])54}55}56if (is.null(ylim)) {57ymax = max(0, apply(positives, FUN = sum, MARGIN = 1))58ymin = min(0, apply(negatives, FUN = sum, MARGIN = 1))59ylim = c(ymin, ymax)60ylim = c( 0.2*floor(10*(ylim[1]+0.1)/2) , 0.2*ceiling(10*(ylim[2]-0.1)/2) )61}62# extend ylim to have extend labels on y-axis6364barplot(t(positives), col = colorset, space = space,65axisnames = axisnames, axes = FALSE, ylim = ylim, ...)66barplot(t(negatives), add = TRUE, col = colorset, space = space,67las = las, xlab = xlab, cex.names = cex.names, axes = FALSE,68ylim = ylim, axisnames = FALSE, ...)69axis(2, col = element.color, las = las, cex.axis = cex.axis,70at=seq( ylim[1], ylim[2] , 0.2 ) , labels = seq( ylim[1], ylim[2] , 0.2 ) )7172if (!is.null(legend.loc)) {73if (legend.loc == "under") {74par(mar = c(0, 2, 0, 1) + 0.1)75plot.new()76if (w.columns < 4)77ncol = w.columns78else ncol = 479legend("center", legend = colnames(w), cex = cex.legend,80fill = colorset, ncol = 3, box.col = element.color,81border.col = element.color)82}83}84#par(op)85}86}8788