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