Tuesday, September 23, 2008

Barplot function in R

Much of my backtesting platform is text driven. Not that I'm opposed to graphs...just felt my time was better spent developing the foundation for the platform before adding bells and whistles. Little did I realize how difficult it is to find a simple graphing engine for the platform. Problem is...I'm old school...couldn't care less about flash graphs. Keep it simple.

Since I'm using python...figured I had to give the matplotlib library a try. It is nice...simple...but something was missing. Couldn't put my finger on it. So, dug around and played with the R language plotting libraries. A bit more my speed...though a bit particular in the settings. Anyway, here's a function I wrote to generate bar charts using R with a replacement for pie charts in mind...


#-----------------------------------------------------------------
# Simple bar chart - use instead of pie chart when possible.
#-----------------------------------------------------------------
barPie <- function(xSeries, chTitle="Your Bar Chart", xLab="X Label",
xDesc="%")
{
xSeries <- sort(xSeries)

# save off original settings in order to reset on exit
oldPar <- par(no.readonly=TRUE)

plot.new()

# set page margins in inches
par(mai=c(1,1.5,1,1))


# pad 30% for labels
# start plotting at 0.0 unless negative
if (min(xSeries) < 0.0)
{
xLim = c((min(xSeries) * 1.3), (max(xSeries) * 1.3))
}
else
{
xLim = c(0.00, (max(xSeries) * 1.3))
}

# horizontal barplot in color baby!
bp <- barplot(xSeries, horiz=T,
xlab=xLab, las=1, col=rainbow(length(xSeries)),
xlim=xLim,
axes=F, cex.names=0.7, main=chTitle)

# if x negative then start label at 0.0
# otherwise, start label at value of x.
xVals = ifelse(xSeries < 0.0, 0.0, xSeries)
text(xVals, bp, paste(xSeries, xDesc, sep=""),pos=4, cex=0.65)

# format x axis
xRange <- formatC(pretty(xSeries), 1, format="f")

axis(1, at=xRange, labels=as.character(xRange), cex.axis=0.75)
box()

#restore par value to previous state
on.exit(par(oldPar))
}


Used data from my portfolio to plot sector allocations and called the function...

sectors <- c(10.64,119.83,162.66,66.48,71.78,35.44,32.77,161.17,53.91,
101.81,53.38,231.45,31.24,103.01)
sectors <- round((sectors/sum(sectors)*100.00), 1)

# write to png driver
png("c:/taylortrade/rlang/sectors_test.png")

barPie(sectors, "Sector Allocation", "Pct Allocated")

# stop writing to png driver
dev.off()


And here's the result...

No comments: