In my continued exploration of C# I recently had the opportunity to investigate the Google Chart API using Google Chart Sharp. Both the C# API and Google Chart itself are great. For those unfamiliar with Google Chart here is a quick summary.
Google Chart allows you to dynamically generate many of the popular types of chart – currently the API includes support for Line Charts, Bar Charts, Pie Charts, Venn Diagrams, plus many more. Check out the full list of chart types here.
Charts are generated via a GET request using a simple URL, where various GET parameters can be supplied to customize the chart. For example, to construct a pie chart that describes web browser usage for a particular page in which FireFox has 60%, and IE 40% of the total views, we use the following URL:
http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=FireFox|IE
Typing this URL into your browser will show the chart below:
I’m sure many of you will recognise the chart design from Google Analytics.
Not only is the Chart API free to use (but not to abuse!), it also generates pretty nifty looking charts.
The charts can also be customised in many different ways including size, colour, axis, etc. Check out the documentation for this on the Google Chart API page linked to above. To show how simple it is to change the colours, take a look at the chart below:
Here the only change required to add custom colours is an additional HTML GET parameter – I simply added chco=9913CE,D3A4E5
to the end of the URL given above.
Now on to the C# side of things.
As you can probably guess, the C# wrapper for Google Chart simply generates a URL. For example, to create the chart above using our new colour scheme we do the following:
1 2 3 4 5 | PieChart chart = new PieChart(250, 100, PieChartType.ThreeD); chart.SetData(new int [] { 60, 40 }); chart.SetPieChartLabels(new string [] { "FireFox", "IE" }); chart.SetDatasetColors(new string [] { "9913CE", "D3A4E5" }); string url= chart.GetUrl(); |
You can then use the URL directly in an HTML document or download the image locally using the following code:
1 2 3 4 | WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Image image = Image.FromStream(response.GetResponseStream()); image.Save("mychart.png"); |
Yep it’s that easy. The other charts can be created just as quickly in both the Google Chart API and also with the C# wrapper. So if you are looking to create good looking charts and don’t want to pay much (any) money I suggest that you check this out.