Liomblr RSS

Archive

May
18th
Tue
permalink

cvp.r

draw.cvp <- function(units, margins,
        names = NULL, fixed.costs = NULL) {

    if (length(units) < 1) { return(NULL) }
    x.lab <- cumsum(c(0, units))

    library(grid)
    grid.newpage()
    vp <- viewport(width=0.8, height=0.8,
            xscale=c(0, sum(units)), yscale=c(0, max(margins)))
    pushViewport(vp)

    grid.xaxis(x.lab)
    grid.yaxis()

    grid.rect(x=head(x.lab, -1), y=0, width=units, height=margins,
            just=c("left", "bottom"), default.units="native",
            gp=gpar(fill=rainbow(length(units))))

    if (!is.null(names)) {
        grid.text(names, x=unit(head(x.lab, -1) + units / 2, "native"),
                y=unit(margins, "native") + unit(1, "char"))
    }

    if (!is.null(fixed.costs)) {
        gp <- gpar(lwd=3)
        grid.move.to(x=x.lab[1], y=fixed.costs[1], default.units="native")
        for (i in 1:length(units)) {
            grid.line.to(x=x.lab[i],
                    y=fixed.costs[i], default.units="native", gp=gp)
            grid.line.to(x=x.lab[i + 1],
                    y=fixed.costs[i], default.units="native", gp=gp)
        }
    }

    popViewport()
    return(vp)
}

dat <- read.csv("data.csv")
draw.cvp(dat$units, dat$margin, dat$product, dat$fixed)