谷歌图表中的层次结构图

时间:2016-10-24 22:56:03

标签: javascript charts google-visualization

我如何构建这样的东西(在其中一个轴上有子类别)enter image description here

1 个答案:

答案 0 :(得分:1)

虽然通过标准配置选项无法提供所请求的布局,但是 如果您可以手动修改svg,则可以实现

当图表的'ready'事件触发时,添加类别标签和组线

请参阅以下工作代码段,这只是展示可能性的一个示例

基于图表的大小和位置做出了几个假设......

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

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['State', 'Store', 'Sales'],
    ['California', 'Donald\'s Market', 1560],
    ['California', 'Alexei\'s Specialties', 1090],
    ['California', '24-Seven', 345],
    ['Texas', 'Albert Market', 245],
    ['Texas', 'Jim\'s Market', 245],
    ['Texas', 'International Food Store', 82]
  ]);

  var options = {
    bars: 'horizontal',
    chartArea: {
      left: 204
    },
    height: 400,
    vAxis: {
      textStyle: {
        fontSize: 10
      }
    }
  };

  var chartDiv = document.getElementById('chart_div');
  var chart = new google.visualization.BarChart(chartDiv);

  var view = new google.visualization.DataView(data);
  view.setColumns([1, 2, {
    calc: 'stringify',
    sourceColumn: 2,
    type: 'string',
    role: 'annotation'
  }]);

  google.visualization.events.addListener(chart, 'ready', function () {
    var rowIndex = -1;
    var stateValue = '';
    var svgParent = chartDiv.getElementsByTagName('svg')[0];
    Array.prototype.forEach.call(chartDiv.getElementsByTagName('text'), function(text) {
      var groupLabel;
      if ((text.getAttribute('text-anchor') === 'end') &&
          (parseFloat(text.getAttribute('x')) < 200)) {
        rowIndex++;
        if (stateValue !== data.getValue(rowIndex, 0)) {
          stateValue = data.getValue(rowIndex, 0);
          groupLabel = text.cloneNode(true);
          groupLabel.setAttribute('x', '60');
          groupLabel.innerHTML = stateValue;
          svgParent.appendChild(groupLabel);
          addGroupLine(groupLabel, -24);
        }
        if (rowIndex === (data.getNumberOfRows() - 1)) {
          addGroupLine(text, 16);
        }
      }
    });

    function addGroupLine(text, yOffset) {
      var groupLine = chartDiv.getElementsByTagName('rect')[0].cloneNode(true);
      groupLine.setAttribute('y', parseFloat(text.getAttribute('y')) + yOffset);
      groupLine.setAttribute('x', '16');
      groupLine.setAttribute('height', '0.8');
      groupLine.setAttribute('width', '188');
      groupLine.setAttribute('stroke', 'none');
      groupLine.setAttribute('stroke-width', '0');
      groupLine.setAttribute('fill', '#000000');
      svgParent.appendChild(groupLine);
    }
  });

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