每7个点一个x轴

时间:2017-01-04 17:27:01

标签: charts google-visualization

area charts中,我想在x轴上每7个点有一个刻度+标签,而不是每个点有一个x轴刻度。如何在以下代码中执行此操作?

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

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2013',  1000,      400],
      ['2014',  1170,      460],
      ['2015',  660,       1120],
      ['2016',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
      hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
      vAxis: {minValue: 0}
    };

    var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }

1 个答案:

答案 0 :(得分:1)

使用hAxis.ticks选项提供自定义 x轴标签

该选项采用数组[]的值,
用于轴的相同类型(数据表中的第一列)
在这种情况下'date'

请参阅以下工作代码段...

  • '12/07/2016'
  • 以来每天添加一个点
  • 每7天添加一个勾号



google.charts.load('current', {
  callback: function () {
    drawChart();
    window.addEventListener('resize', drawChart, false);
  },
  packages:['corechart']
});

function drawChart() {
  var formatDate = new google.visualization.DateFormat({
    pattern: 'MMM d'
  });

  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('date', 'Day');
  dataTable.addColumn('number', 'Y');
  dataTable.addColumn({role: 'style', type: 'string'});

  var oneDay = (1000 * 60 * 60 * 24);
  var startDate = new Date(2016, 11, 7);
  var endDate = new Date();
  var ticksAxisH = [];
  for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneDay) {
    // set row date
    var rowDate = new Date(i);
    var xValue = {
      v: rowDate,
      f: formatDate.formatValue(rowDate)
    };

    // y = 2x - 8
    var yValue = (2 * ((i - startDate.getTime()) / oneDay) - 8);

    dataTable.addRow([
      xValue,
      yValue,
      'point {fill-color: #003eff;}, line {stroke-color: #003eff;}'
    ]);

    // add tick every 7 days
    if (((i - startDate.getTime()) % 7) === 0) {
      ticksAxisH.push(xValue);
    }
  }

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.AreaChart(container);
  chart.draw(dataTable, {
    colors: ['#e6f4f9'],
    areaOpacity: 1.0,
    hAxis: {
      gridlines: {
        color: '#f5f5f5'
      },
      ticks: ticksAxisH
    },
    legend: 'none',
    pointSize: 4,
    vAxis: {
      gridlines: {
        color: '#f5f5f5'
      }
    },
  });
}
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;
&#13;
&#13;