chartsgoogle-visualizationgoogle-pie-chart

Google Charts Legend labels cut off


The legend labels for my pie chart are being cut off when the label is too long. I have already tried to setting width to '100%' but my legend is way big to counter that. Is there a way to discretely define the pie chart size and the legend size? Could someone please share a working example of the same.

Link for JS Fiddle: https://jsfiddle.net/2nzzLe18 The container div dimensions and the legend label font size are part of my requirement.

Also below is the code,

  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['info regarding task Work',     11],
      ['info regarding task Eat',      2],
      ['info regarding task Commute',  2],
      ['info regarding task Watch TV', 2],
      ['info regarding task Sleep',    7]
    ]);

    var options = {
      title: 'My Daily Activities',
      chartArea: {left: -100, width: '100%'},
      legend: {textStyle: {fontSize: 15}},

    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }

Thanks, Farhan


Solution

  • it can be cumbersome to properly size a pie chart,
    but it boils down to adjusting the size of the overall chart div,
    and the size of the chartArea, where the pie is drawn (separate from the legend)

    it can be tricky because it doesn't always respond how you think it should,
    but I was able to get the entire legend to display

    see the following working snippet,
    moved the overall size from the style attribute on the div
    to the options for the chart, then adjusted the chartArea

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['info regarding task Work',     11],
        ['info regarding task Eat',      2],
        ['info regarding task Commute',  2],
        ['info regarding task Watch TV', 2],
        ['info regarding task Sleep',    7]
      ]);
    
      var options = {
        backgroundColor: 'cyan',
        title: 'My Daily Activities',
        chartArea: {
          left: 0,
          height: 250,
          width: 600
        },
        height: 300,
        width: 600,
        legend: {
          maxLines: 1,
          textStyle: {
            fontSize: 15
          }
        },
      };
    
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(data, options);
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="piechart"></div>