Alex KeySmith Alex KeySmith - 7 months ago 76
Javascript Question

How to write a custom formatter for Google DataTables (for use on visualisation api)

I'm looking to format my data in which I replace numbers with icons.

As far as I can tell Google do not currently have a formatter to do so:

There is a brief mention within the documents about custom formatters, but I cannot seem to find any documents on how to begin writting a custom formatters.

Can anyone point me in the right direction?

There is a similar question on StackOverflow: Write a custom formatter for Google Charts Api . However the question was resolved simply using the built-in formatters (which I don't think I can use).

oli oli

I don't think you'll be able to make the current formatters to do what you want, but you should be able to make your own formatter easily enough. I put together iconFormatter below for a sample - this could be adjusted to do whatever you need really.

<html xmlns="">
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['table']});
    <script type="text/javascript">
      * Gviz icon formatter
      * @param {Object<Number, String>} Map of numbers to icon URIs
      var iconFormatter = function(iconMap) {
        this.iconMap = iconMap;
       * Formats a gviz DataTable column
       * @param {Object} dt DataTable to format
       * @param {Number} column index number
      iconFormatter.prototype.format = function(dt, column) {
        for (var i=0;i<dt.getNumberOfRows();i++) {
          var formattedValue = this.iconMap[dt.getValue(i, column)];
          var htmlString = "<img src="+formattedValue+" />";
          dt.setFormattedValue(i, column, htmlString);
          // underlying value preserved
          console.log(dt.getValue(i, column)); 
      function drawVisualization() {
        // Create and populate the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Height');
        data.setCell(0, 0, 'Tong Ning mu');
        data.setCell(1, 0, 'Huang Ang fa');
        data.setCell(2, 0, 'Teng nu');
        data.setCell(0, 1, 174);
        data.setCell(1, 1, 523);
        data.setCell(2, 1, 86);

        var iconMap = {
          174: "",
          523: "",
          86: ""
          // other numbers

        // Create and draw the visualization.
        visualization = new google.visualization.Table(document.getElementById('table'));
        // apply our formatter, just like normal
        var formatter = new iconFormatter(iconMap);
        formatter.format(data, 1);
        // allow html, just like any html formatter will require
        visualization.draw(data, {allowHtml: true});
    <div id="table"></div>

Hope that helps.