Wednesday, May 7, 2008

Google chart API in .NET

Yes I know - there are good .NET libraries for using google chart API, but I was interested to dig a little bit deeper into google chart API. And I have to say that google chart is worse than opensource program GNUPLOT (in the sense of functionality), but ok whatever... And second target was - to have as less code (including libraries) as possible for charting VERY simple XY graphs. So after studing a bit google chart documentation- I wrote very primitive class for plotting simple XY graph. For plotting graphs with this code you need:
- Internet connection
- .NET framework 3.5
- Internet browser (whatever you like)
So this is the code:




class Program
{
static void Main(string[] args)
{
double[] xval;
double[] ysin, yexp;

xval = new double[] { 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5 };
ysin = Array.ConvertAll(xval, v => { return Math.Sin(v); });
yexp = Array.ConvertAll(xval, v => { return Math.Exp(v); });

GoogleChart.PlotLineChart(xval, ysin, "x values", "sin(x)", "sin(x) function", null);
GoogleChart.PlotLineChart(xval, yexp, "x values", "exp(x)", "exp(x) function", null);
}
}

class GoogleChart
{
public static void PlotLineChart(double[] Xvalues,
double[] Yvalues,
string Xlabel,
string Ylabel,
string Title,
string imgsize)
{
string urltemplate = "http://chart.apis.google.com/chart?cht=lxy&chs=@imgsize@&chd=t:@xvalues@%7C@yvalues@&chds=@xmin@,@xmax@,@ymin@,@ymax@&chxr=0,@xmin@,@xmax@%7C1,@ymin@,@ymax@&chxt=x,y,x,y&chxl=2:%7C@xlabel@%7C3:%7C@ylabel@%7C&chxp=2,50%7C3,50&chtt=@title@";
string xvalagg = Xvalues.Aggregate("", (old, next) =>
old + ((old == "") ? "" : ",") + next.ToString(CultureInfo.InvariantCulture));
string yvalagg = Yvalues.Aggregate("", (old, next) =>
old + ((old == "") ? "" : ",") + next.ToString(CultureInfo.InvariantCulture));

if (imgsize == null) imgsize = "300x200";

urltemplate = urltemplate.Replace("@imgsize@", imgsize);
urltemplate = urltemplate.Replace("@xvalues@", xvalagg);
urltemplate = urltemplate.Replace("@yvalues@", yvalagg);
urltemplate = urltemplate.Replace("@xmin@", Xvalues.Min().ToString(CultureInfo.InvariantCulture));
urltemplate = urltemplate.Replace("@xmax@", Xvalues.Max().ToString(CultureInfo.InvariantCulture));
urltemplate = urltemplate.Replace("@ymin@", Yvalues.Min().ToString(CultureInfo.InvariantCulture));
urltemplate = urltemplate.Replace("@ymax@", Yvalues.Max().ToString(CultureInfo.InvariantCulture));
urltemplate = urltemplate.Replace("@xlabel@", Xlabel);
urltemplate = urltemplate.Replace("@ylabel@", Ylabel);
urltemplate = urltemplate.Replace("@title@", Title);

System.Diagnostics.Process.Start(urltemplate);
}
}


With this sample code there are generated these nice graphs:


This is it. Have fun with charting !

No comments:

Post a Comment

Comment will be posted after comment moderation.
Thank you for your appreciation.