Google Charts Legend labels cut off

对着背影说爱祢 提交于 2020-12-30 05:59:54

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/39844959/google-charts-legend-labels-cut-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!