Search code examples
google-visualization

When using a date column, first and last bars are cut in half


When I use a column type of date, the first and last bars in the ColumnChart are cut in half. It seems to be rendering from mid-bar. It doesn't do this with non-date sets of data.

Is there any way to fix this so that the complete bars are rendered, with some extra padding?

http://jsfiddle.net/7tHVN/


Solution

  • I had this exact problem (my labels were also weirdly misaligned) and it drove me crazy trying to figure it out. hAxis.viewWindowMode usually fixes issues like this, but it's not possible to use this with date values.

    What I ended up doing was just scrapping the date type entirely, specifying the string type for that column instead, and converting each JS date object to a string representation before adding it to the DataTable, thusly:

    data.addColumn('string', 'Date');
    data.addColumn('number', 'Performance');
    
    var dates = [new Date('2012-4-12'),
                 new Date('2012-4-13'),
                 new Date('2012-4-14')];
    var performance = [59, 35, 86];
    
    var dateString;
    for (var i=0; i<dataForChart.length; i++) {
        dateString = (dates[i].getMonth()+1)+'/'+ // JS months are 0-indexed
                      dates[i].getDate()+'/'+
                      dates[i].getYear();
        data.addRow([dateString, 
                    performance[i]]);
    }
    

    This forces the chart to render with a discrete rather than continuous axis, which fixes the cut-off bars problem. As long as your data and dates are spaced along even intervals (once a day, once a week, etc.) and you pass them in in the proper order, this approach should work.

    There's more info on discrete vs. continuous axes in the Google Viz docs: https://google-developers.appspot.com/chart/interactive/docs/customizing_axes