Add subtitle in AreaChart in google chart?

2019-01-29 02:29发布

问题:

I have successfully implemented AreaChart using google Chart(google-visualization),but now my need to add subtitle in the google AreaChart. Here the code which i have tried.

           var options = {
            width: 310,
            height: 260,
      chart: {
        title: 'Company Performance',
        subtitle: 'Sales, Expenses, and Profit: 2014-2017',
      },
           backgroundColor: '#000000'
        };

回答1:

chart.subtitle is only available to material charts

material charts use packages: ['bar', 'line', 'scatter']
and namespce --> google.charts

unfortunately, no material version of area charts...


chart.subtitle is not available to core charts

core charts use packages: ['corechart']
and namespce --> google.visualization


but you could try adding your own subtitle, when the 'ready' event fires

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable({
      "cols": [
        {"label": "Country", "type": "string"},
        {"label": "Value", "type": "number"}
      ],
      "rows": [
        {"c": [{"v": "Canada"}, {"v": 33}]},
        {"c": [{"v": "Mexico"}, {"v": 33}]},
        {"c": [{"v": "USA"}, {"v": 34}]}
      ]
    });

    var container = document.getElementById('chart_div');
    var chart = new google.visualization.AreaChart(container);
    var options = {
      height: 400,
      legend: {
        position: 'labeled'
      },
      sliceVisibilityThreshold: 0,
      title: 'Title',
      width: 600
    };

    google.visualization.events.addListener(chart, 'ready', function () {
      Array.prototype.forEach.call(container.getElementsByTagName('text'), function(label) {
        if (label.innerHTML === options.title) {
          var subtitle = label.parentNode.appendChild(label.cloneNode(true));
          subtitle.innerHTML = 'Subtitle';
          subtitle.setAttribute('y', parseFloat(label.getAttribute('y')) + 20);
        }
      });
    });

    chart.draw(data, options);
  },
  packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>