Google图表上的标签在特定配置下不可见

时间:2018-11-16 10:28:23

标签: javascript charts google-visualization label

我已经像工作jsfiddle中那样配置了图表。 我已经配置了标签(基于Google文档文档:https://developers.google.com/chart/interactive/docs/gallery/barchart#labeling-bars) 但是它们不可见。当我将图表类型更改为google.visualization.BarChart时,会出现标签,但条形结构会被破坏。如何在我的配置中添加标签?

已复制: https://jsfiddle.net/41fmq37j/

JS:

google.charts.load('current', {'packages':['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
    var data = google.visualization.arrayToDataTable([
        [{label: 'Year', id: 'year', type: 'number'},
        {label: 'Sales', id: 'Sales', type: 'number'},
        {label: 'Expenses', id: 'Expenses', type: 'number'},
  { role: 'annotation' }],
        [2014, 10, 400  ,'label1'],
        [2014, 800, 100 ,'label2'],
        [2015, 200, 460 ,'label3'],
        [2015, 110, 660 ,'label4'],
        [2016, 100, 300 ,'label5'],
        [2016, 600, 120 ,'label6'],
        [2017, 360, 540 ,'label7'],
        [2017, 300, 500 ,'label8']
    ]);

    var options = {
        chart: {
            title: 'Sales and Expenses',
            subtitle: 'Some descr',
        },
        bars: 'horizontal',
        height: 400,
        isStacked: true,
    };

var chart = new google.charts.Bar(document.getElementById('chart_div'));

    chart.draw(data, google.charts.Bar.convertOptions(options));
}

HTML:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
       <div id="chart_div"></div>

编辑:

是否可以像下面这样配置yAxis?因为当前格式可能会造成混淆。 enter image description here

我想创建更多,略有不同的图形,例如,它将按字符串对条进行分组。因此,另一个问题是:如何将按字符串分组的yAxis归档?也许我们应该创建任何比较器?

1 个答案:

答案 0 :(得分:1)

材料图表不支持列角色,例如'annotation'
连同several other options

,并且经典图表

中每个标签不可能有多个堆栈

这样,我们可以使用材料图表,
并手动添加我们自己的注释,
在图表的'ready'事件

请参阅以下工作片段...

google.charts.load('current', {
  packages:['bar']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    [
      {label: 'Year', id: 'year', type: 'number'},
      {label: 'Sales', id: 'Sales', type: 'number'},
      {label: 'Expenses', id: 'Expenses', type: 'number'},
      {role: 'annotation', type: 'string'}
    ],
    [2014, 10, 400, 'label1'],
    [2014, 800, 100, 'label2'],
    [2015, 200, 460, 'label3'],
    [2015, 110, 660, 'label4'],
    [2016, 100, 300, 'label5'],
    [2016, 600, 120, 'label6'],
    [2017, 360, 540, 'label7'],
    [2017, 300, 500, 'label8']
  ]);

  var options = {
    chart: {
      title: 'Sales and Expenses',
      subtitle: 'Some descr',
    },
    bars: 'horizontal',
    height: 400,
    isStacked: true,
    vAxis: {
      format: '0'
    }
  };

  var container = document.getElementById('chart_div');
  var chart = new google.charts.Bar(container);

  // add annotations
  google.visualization.events.addListener(chart, 'ready', function () {
    var annotation;
    var bars;
    var copyLabel;
    var coordsBar;
    var coordsLabel;
    var labels;
    var svg;

    // get svg
    svg = container.getElementsByTagName('svg')[0];

    // find label to clone
    labels = svg.getElementsByTagName('text');
    Array.prototype.forEach.call(labels, function(label) {
      if (label.textContent === data.getValue(0, 0).toString()) {
        copyLabel = label;
      }
    });

    // find top bars, add labels
    bars = svg.getElementsByTagName('path');
    Array.prototype.forEach.call(bars, function(bar, index) {
      coordsBar = bar.getBBox();
      annotation = copyLabel.parentNode.insertBefore(copyLabel.cloneNode(true), copyLabel);
      coordsLabel = annotation.getBBox();
      annotation.textContent = data.getValue(index, 3);
      annotation.setAttribute('fill', '#000000');
      annotation.setAttribute('x', coordsBar.x + coordsBar.width - 16);
      annotation.setAttribute('y', coordsBar.y + coordsBar.height - (coordsLabel.height / 2));
      annotation.style.zIndex = -1;
    });
  });

  chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


编辑

注释脚本找到第一个y轴标签,
并将其用作注释的副本。
如果y轴的值发生变化,
然后查找标签的脚本需要更改。

已在此处更新...

// find label to clone
labels = svg.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
  // find first y-axis label
  if (label.textContent === formatDate.formatValue(data.getValue(0, 0))) {
    annotation = label;
  }
});

请参阅以下工作片段...

google.charts.load('current', {
  packages:['bar']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    [
      {label: 'Date', id: 'string', type:'date'},
      {label: 'Sales', id: 'Sales', type: 'number'},
      {label: 'Expenses', id: 'Expenses', type: 'number'},
      {role: 'annotation', type: 'string'}
    ],
    [new Date('2011-12-20'), 10, 400, 'User1'],
    [new Date('2011-12-20'), 800, 100, 'User2'],
    [new Date('2011-12-21'), 200, 460, 'User3'],
    [new Date('2011-12-21'), 200, 460, 'User3'],
  ]);

  var dateFormat = 'YYYY/MM/dd';

  var options = {
    chart: {
      title: 'Sales and Expenses',
      subtitle: 'Some descr',
    },
    bars: 'horizontal',
    height: 400,
    isStacked: true,
    vAxis: {
    		format: dateFormat,

    }
  };

  var container = document.getElementById('chart_div');
  var chart = new google.charts.Bar(container);
  var formatDate = new google.visualization.DateFormat({
    pattern: dateFormat
  });

  // add annotations
  google.visualization.events.addListener(chart, 'ready', function () {
    var annotation;
    var bars;
    var copyLabel;
    var coordsBar;
    var coordsLabel;
    var labels;
    var svg;

    // get svg
    svg = container.getElementsByTagName('svg')[0];

    // find label to clone
    labels = svg.getElementsByTagName('text');
    Array.prototype.forEach.call(labels, function(label) {
      // find first y-axis label
      if (label.textContent === formatDate.formatValue(data.getValue(0, 0))) {
        copyLabel = label;
      }
    });

    // find top bars, add labels
    bars = svg.getElementsByTagName('path');
    Array.prototype.forEach.call(bars, function(bar, index) {
      coordsBar = bar.getBBox();
      annotation = copyLabel.parentNode.insertBefore(copyLabel.cloneNode(true), copyLabel);
      coordsLabel = annotation.getBBox();
      annotation.textContent = data.getValue(index, 3);
      annotation.setAttribute('fill', '#ffffff');
      annotation.setAttribute('text-anchor', 'start');
      annotation.setAttribute('x', coordsBar.x + coordsBar.width);
      annotation.setAttribute('y', coordsBar.y + (coordsBar.height / 2) + (coordsLabel.height / 2));
      annotation.style.zIndex = -1;
    });
  });

  chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>