One x-axis tick every 7 points

只愿长相守 提交于 2019-12-23 02:45:47

问题


In area charts, I'd like to have a tick + label on x-axis every 7 points only, instead of one x-axis-tick per point. How to do that in the following code?

  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:


use the hAxis.ticks option to provide custom x-axis labels

the option takes an array [] of values,
of the same type used for the axis (first column in the data table)
in this case 'date'

see following working snippet...

  • a point is added for each day since '12/07/2016'
  • a tick is added every 7th day

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'
      }
    },
  });
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


来源:https://stackoverflow.com/questions/41469849/one-x-axis-tick-every-7-points

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