#!/usr/bin/r -pi # # script to generate chart for dog-food experiment # # -- where to look for R libraries .libPaths(c('~/local/lib/R', '/usr/lib/R/library', '/usr/lib/R/site-library' )) # # require needed libraries: # suppressPackageStartupMessages(library(ggplot2)) # for date breaks/formatting functions suppressPackageStartupMessages(library(scales)) # # Graphical constants # Default chart width and height, resolution, font-size # (ggplot saves too big files by default) # golden.ratio = 1.61803399887 W = 4.0 H = W / golden.ratio DPI = 200 FONTSIZE=8 # # Theme definitions # title.theme = theme_text(family="FreeSans", face="bold.italic", size=FONTSIZE) y.label.theme = theme_text(family="FreeSans", face="bold.italic", size=FONTSIZE-2, angle=90) x.label.theme = theme_text(family="FreeSans", face="bold.italic", size=FONTSIZE-2) x.axis.theme = theme_text(family="FreeSans", face="bold", size=FONTSIZE-2, colour="grey50") y.axis.theme = theme_text(family="FreeSans", face="bold", size=FONTSIZE-2, colour="grey50") # # generate_chart # Generic function to generate one (Y = f(time)) time-series chart # with a LOESS smoothed line, and monthly x-axis labeling # generate_chart <- function( data=d, x, y, title='The title', ylab='The Y-axis label', xlab='The X-axis label', file='thechart.png' ) { the.aes <- eval(substitute(aes(x, y), list(x = substitute(x), y = substitute(y)))) ggplot(data=d, the.aes) + geom_smooth(method='loess') + geom_point(aes(color=Brand), pch=20, cex=5) + opts(title=title, plot.title=title.theme, axis.title.y=y.label.theme, axis.title.x=x.label.theme, axis.text.x=x.axis.theme, axis.text.y=y.axis.theme ) + scale_x_continuous(xlab, breaks=c(1,2,3,4,5), labels=c('$1.0','$2.0','$3.0','$4.0','$5.0')) + scale_y_continuous(ylab, breaks=c(2.0,2.5,3.0,3.5,4.0), labels=c('2.0','2.5','3.0','3.5','4.0')) ggsave(file=file, width=W, height=H, dpi=DPI) } # # main # if (! exists('argv') || is.null(argv) || (length(argv) < 1)) { argv <- c('dogpref.csv') } csvfile <- argv[1] # # -- read the CSV data into data-frame 'd' # d <- read.csv(csvfile, h=T) # # Calculate new columns from existing ones and convert date type # d <- transform(d, price.per.pound=price/weight ) # # Generate the price-per-pound vs dog-preference chart # generate_chart( data=d, x=price.per.pound, y=preference, title='Dog food Preference vs Price/Pound', ylab='Preference (Higher is preferred)', xlab='Price / Pound', file='dogpref.png' ) warnings()