radiantstatic radiantstatic - 2 months ago 31
Javascript Question

Google Charts Timeline - How to Force Bar Labels INSIDE of Bar

I am using Google's charts library to generate a Gantt-like chart (using Timeline). One issue I am running into is the library's automatic

barLabel
placement. It's terribly inconsistent in when it should truncate long strings to put inside the label versus placing the full string outside of the label.

Question

How can I force text to always sit inside the bar?

Example:

Example of text placement issue in Google Charts

Answer

The solution:

Required a little tweaking from @WhiteHat's response but here it is!

google.visualization.events.addOneTimeListener(chart, 'ready', function () {
        var rectangles = container.getElementsByTagName('rect');
        var adjustY = 25;
        var adjustX = 15;
        for(var i=0; i<rectangles.length; i++){
            if (rectangles[i].getAttribute('x') !== '0') {
                var barLabel = container.appendChild(document.createElement('span'));
                barLabel.innerHTML = dataTable.getValue(i, 1);
                barLabel.style.color = '#000';
                barLabel.style.position = 'absolute';
                barLabel.style.overflow = 'hidden';
                barLabel.style.width = (parseInt(rectangles[i].getAttribute('width') - adjustX)) + 'px';
                barLabel.style.top = (parseInt(rectangles[i].getAttribute('y')) + adjustY) + 'px';
                barLabel.style.left = (parseInt(rectangles[i].getAttribute('x')) + adjustX) + 'px';
            }
        }

    });

chart.draw(dataTable, {
    timeline: {
       showBarLabels: false
    }
});
Comments