Search code examples
javascriptgoogle-visualizationtreemap

Is there a way to display the children labels in Google Charts' TreeMap


I'm trying to create a TreeMap using Google Charts that not only shows the parent label along with the children's color breakdowns, but also the children's labels. I basically want this (save possible children coloration): enter image description here

I haven't found any online examples or questions on it, is this possible?


Solution

  • not sure that you can get exactly like the picture,
    but if you want to show both the parent and child labels,
    use option --> maxDepth: 2

    note: duplicate child id's are not allowed,
    here, object notation is used to provide a unique id,
    but still display the same name on multiple nodes

    {v: 'Rick0', f: 'Rick'}
    {v: 'Rick1', f: 'Rick'}
    

    where...
    v: = value
    f: = formatted value

    see following working snippet...

    google.charts.load('current', {
      packages: ['treemap']
    }).then(function () {
      var data = google.visualization.arrayToDataTable([
        ['Person', 'Fruit', 'Size', 'Color'],
        ['Global', null, 0, 0],
        ['Bananas', 'Global', 0, 0],
        [{v: 'Rick0', f: 'Rick'}, 'Bananas', 100, 0],
        [{v: 'Anne0', f: 'Anne'}, 'Bananas', 40, 0],
        [{v: 'Peter0', f: 'Peter'}, 'Bananas', 5, 0],
        ['Apples', 'Global', 0, 0],
        [{v: 'Anne1', f: 'Anne'}, 'Apples', 20, 2],
        [{v: 'Peter1', f: 'Peter'}, 'Apples', 20, 2],
        [{v: 'Rick1', f: 'Rick'}, 'Apples', 15, 2],
        ['Oranges', 'Global', 0, 0],
        [{v: 'Rick2', f: 'Rick'}, 'Oranges', 20, 1],
        [{v: 'Peter2', f: 'Peter'}, 'Oranges', 20, 1],
        [{v: 'Anne2', f: 'Anne'}, 'Oranges', 10, 1],
        ['Susanne', 'Global', 10, null]
      ]);
    
      tree = new google.visualization.TreeMap(document.getElementById('chart_div'));
      tree.draw(data, {
        maxDepth: 2,
        minColor: 'yellow',
        midColor: 'orange',
        maxColor: 'red',
        noColor: 'lime',
      });
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>