Monday, August 11, 2014

Google Charts: How to change axis, legend styles beyond what is provided by the API

If you are familiar with Google Charts, you know that you need to pass a 'Configuration Options' object when drawing a chart. Properties of that object for bar charts are found here.

For a recent project I worked, I needed to show the axis and legend labels as 'clickable' links hence I needed to show the cursor as a 'hand/pointer' when hovered above them. But Google Charts API only provides a limited set of styling for axis and legend labels. More precisely it only supports color, fontName, fontSize, bold, italic & underline styles.

But after inspecting the generated HTML DOM for the charts, I figured out a simple way to manipulate the elements properties and change the styling the way you want.

I prefer jQuery so here goes how the vertical axis labels were manipulated:
 $('text[text-anchor=end]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

Here's how the horizontal axis labels were manipulated:
 
 $('text[text-anchor=middle]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

Here's how the legend labels were manipulated:
 
 $('text[text-anchor=start]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

If you are a plain JavaScript guy, here you go:
 
 var labels = document.querySelectorAll('text[text-anchor=end]');
 for (var i = 0; i < labels.length; i++) {
  labels[i].setAttribute('cursor', 'pointer');
  ...
 }

Make sure you understand that the above hacks basically set the styling to every matching element found on the page. So if you have multiple charts on the same page and you need styling done individually, you will have to check additional properties of those elements inside the loops to determine which chart they belong to.

If you need further clarification on this, post it as a comment :)

No comments:

Post a Comment