radiantstatic radiantstatic - 1 month ago 10x
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

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.


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


Example of text placement issue in Google Charts


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