public
Created

horizon in base graphics

  • Download Gist
horizon in base.r
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
require(RColorBrewer)
require(quantmod)
require(PerformanceAnalytics)
 
data(managers)
 
#let's do managers from 2002 to 2004 to get positive and negative
x <- cumprod(1+managers["2002::2004"])[,1] - 1
 
#get some decent colors from RColorBrewer
#we will use colors on the edges so 2:4 for red and 7:9 for blue
col.brew <- brewer.pal(name="RdBu",n=10)
 
#get this to ease using it later
n<-nrow(x)
 
#set scale to be 10%
horizonscale=0.1
#remove space around chart
par(mar=c(2,1,1,1))
plot(index(x), coredata(x), type="n", bty="n", las=1, yaxt="n", xlab=NA, ylab=NA, ylim=c(-horizonscale,horizonscale))
#thanks http://stackoverflow.com/questions/9630014/polygon-for-xts-objects
#draw first positive band
polygon(
index(x)[c(1,1:n,n)],
c(0,ifelse(coredata(x) > 0,coredata(x), 0),0),
col=col.brew[7]
)
#draw first negative band
polygon(
index(x)[c(1,1:n,n)],
c(0,ifelse(coredata(x) < 0 ,coredata(x), 0),0),
col=col.brew[4]
)
#overlay second positive band
polygon(
index(x)[c(1,1:n,n)],
c(0,ifelse(coredata(x) > 0.1,coredata(x) - 0.1, 0),0),
col=col.brew[8]
)
#overlay second negative band
polygon(
index(x)[c(1,1:n,n)],
c(0,ifelse(coredata(x) < -0.1 ,coredata(x) + 0.1, 0),0),
col=col.brew[3]
)
#overlay third positive band
polygon(
index(x)[c(1,1:n,n)],
c(0,ifelse(coredata(x) > 0.2 ,coredata(x) - 0.2, 0),0),
col=col.brew[9]
)
#overlay third negative band
polygon(
index(x)[c(1,1:n,n)],
c(0,ifelse(coredata(x) < -0.2 ,coredata(x) + 0.2, 0),0),
col=col.brew[2]
)
#little touch up to get a line at extending left to right
abline(h=0,col="black")
#add a line at the bottom of the chart
abline(h=par("usr")[3],col="black")
 
 
#now let's do it with a loop and flip the negative up
nbands = ceiling(max(abs(coredata(x)))/horizonscale)
plot(index(x), abs(coredata(x)), type="n", bty="n", las=1, yaxt="n", xaxt="n", xlab=NA, ylab=NA, ylim=c(0,horizonscale))
#thanks to helpful reader A. Zolot
par(usr=c(index(x)[1],index(x)[n],0,horizonscale),mar=c(2,1,1,1)) # 0-margines
for (i in 1:nbands) {
#draw positive
polygon(
c(index(x)[1], index(x), index(x)[n]),
c(0, coredata(x) - (i-1) * horizonscale,0),
col=col.brew[length(col.brew)-nbands+i-1],
border=NA
)
#draw negative
polygon(
c(index(x)[1], index(x), index(x)[n]),
c(0, -coredata(x) - (i-1) * horizonscale, 0),
col=col.brew[nbands-i+1],
border=NA
)
}
abline(h=0,col="black")
axis.Date(side=1,x=index(x),pos=0)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.