The Google Chart API dynamically generates a variety of chart types by returning a PNG-format image in response to a given URL. Within the URL you can specify the various attributes of the chart such as the chart data set, image size, title and axis labels. For example click the below URL which will generate a pie chart (cht=p3) with a 60% - 40% split (chd=t:60,40):
http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250×100&chl=Hello|World
Having played with the API a bit further I wanted the capability to dynamically generate a data set for a given function e.g. f(x) = log(x) and construct the corresponding Google Chart API URL to plot the graph. I’ve achieved this using JavaScript and the below graph demonstrates the code in use. Clicking the links below the graph fires an event that will generate the data set and URL for the given function. The image source is then set to the URL. Wikipedia is a representation of an example function illustrated on the Wikipedia Function (mathematics) page.
f(x) = log(x) | f(x) = sin(x) | f(x) = cos(x) | f(x) = 2^x | Wikipedia
The JavaScript API is used as below (e.g. for the log graph). I’ll post comment on the rest of the code soon, but in meantime the full source code can be found here: /wp-includes/js/myjs/graphing.js. The graphDataSetBuilder function returns a closure which is only invoked when the corresponding link for the function is hit. This allows you to provide parameters for the function prior to it being executed. The usage here is almost the same as the setTimeout example on jibbering.com
//Prepare a dataset for the given min X value, max X value,
//interval and function
var logDataSet = graphDataSetBuilder(0, 10,
1,function (x) {return Math.log(x)});
//Generate Google Chart URL using googleIt() function, passing
//in the dataset above. Set the image source to the URL
document.graph.src=googleIt(logDataSet());


No Responses
No comments yet.