Creating Google Bar Chart in SharePoint 2010
In my last blog post, I wrote about creating a Pie Chart in SharePoint using Google charts. In this post, I will show how to create a bar chart using the same data. It’s going to be a short post because it requires changing one line.
Before I proceed to the purpose of this post, I wanted to first share some information I found on knowing when to use the right type of chart. It’s always convey your data in a manner that makes sense. I found the following sites to be useful.
For the sake of example, my posts just show how to use Google chart and not necessarily focused on selecting the right one.
Now that we have that out of the way, to convert the pie chart to a bar chart, all you have to do is change the following line:
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
to
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
Now you are probably wondering, how is this able to work? Well, if you remember in my last post, I talked about how every chart has a data format that needs to be followed. Here’s the data format for both pie and bar charts:
Pie Chart
Rows: Each row in the table represents a slice.
Bar Chart
Rows: Each row in the table represents a group of bars.
As you can see the data format is similar and that’s why we are able to change one line of code to make it work.
To render it in SharePoint, I created another content editor web part on the same page as my Pie Chart and I also created another file called BuildBarChart.html with the following code in it:
</pre> <div id="BarChart_div" style="width: 650px; height: 500px;"> </div> <pre>
I also created a function called drawBarChart() but has the same exact code as my pieChart. The only difference is the line I talked about above.
Here’s the code of the function:
function drawBarChart(BinderItems,PencilItems,PenItems,PenSetItems,DeskItems) { //alert("Desk Items: "+DeskItems); var data = google.visualization.arrayToDataTable([ ['Items', 'Number of Items Available'], ['Binder', BinderItems], ['Pencils', PencilItems], ['Pen Set', PenSetItems], ['Pen', PenItems], ['Desk', DeskItems] ]); var options = { title: 'Available School Items', is3D:true, titleTextStyle: {color: 'black', fontName:'"Verdana"', fontSize: '12'}, legend: { textStyle: {color: 'black', fontName: '"Arial"', fontSize: '12'}} }; var chart = new google.visualization.BarChart(document.getElementById('BarChart_div')); chart.draw(data, options); }
Here are both charts side by side. Pie and Bar Charts
Please share your comments. I would appreciate feedback. Thanks!
Alexander Bautz released a jquery solution that provided end users a no-code interface for Google charts: http://spjsblog.com/2010/08/26/interactive-charts-using-google-visualization-api-v2-0/