# Andy Eggers, April 2, 2008 # quick R API for google charts # see http://code.google.com/apis/chart/ googleplot = function(x, y, xlim = NULL, ylim = NULL, pch = 1, width = 250, height = 200){ if (length(x) != length(y)){stop("Length of x and y differ")} if (is.null(xlim)){x_spread = max(x) - min(x); xlim = c(min(x) - .1*x_spread, max(x) + .1*x_spread)} #TODO: use standard approaches for making reasonable axes, if possible if (is.null(ylim)){y_spread = max(y) - min(y); ylim = c(min(y) - .1*y_spread, max(y) + .1*y_spread)} encoded_x = simple_encode(x, xlim[1], xlim[2]) encoded_y = simple_encode(y, ylim[1], ylim[2]) if (length(pch) != length(x)){ cat("repeating ", pch[1], "\n", sep = "") fixed_pch = rep(pch[1], length(x)) } else {fixed_pch = pch} encoded_pch = simple_encode(20*fixed_pch, the_min = 0) # TODO: rethink pch handling preamble = "http://chart.apis.google.com/chart?cht=s" chart_data = paste("chd=s:", paste(join_string(encoded_x), join_string(encoded_y), join_string(encoded_pch), sep = ","), sep = "") axis_declaration = "chxt=x,y" # x- and y-axis for now axis_labels = paste("chxl=0:|", axis_labels(xlim), "|1:|", axis_labels(ylim), sep = "") chart_size = paste("chs=", as.character(width), "x", as.character(height), sep = "") paste("", sep = "") } simple_encode = function(vec, the_min = NULL, the_max = NULL){ if (is.null(the_min)){the_min = min(vec)} # take up the whole range of values if no min and max was provided if (is.null(the_max)){the_max = max(vec)} rescaled_vec = 61 * (vec - the_min)/the_max # simple text encoding produces single character data values A-Za-z0-9 c(LETTERS, letters, 0:9)[floor(rescaled_vec)+1] # see http://code.google.com/apis/chart/#simple } # utility for concatenating strings from vectors to pass data to API join_string = function(vec, sep = ""){ out = vec[1] for (element in vec[2:length(vec)]){ out = paste(out, element, sep = sep) } out } axis_labels = function(lim_pair, length = 5){ # TODO: use standard approaches for choosing tick marks vec = floor(seq(from = lim_pair[1], to = lim_pair[2], length.out = length)) join_string(vec, sep = "|") }