0
votes

I am using Google Charts - Line Chart to show a weeks trend(x-axis) to Cost(y-axis). Now if i span the number of weeks in past 9 months, then most of the x-axis labels are hidden because of the space constraint. I am trying to show an axis label only for the first week of a month and have set blank to the rest.

Is there a way to show all of the 9 labels(first week of each month) for 9 months

1

1 Answers

1
votes

to show specific axis labels, use config option --> hAxis.ticks

ticks takes an array of values, each value will be shown as a label.
the value should be the same type as the x-axis values in the data table.

if you are using dates, then the array should be filled with date values.

hAxis: {
  ticks: [new Date(2018, 0, 1), new Date(2018, 1, 1), new Date(2018, 2, 1), ...]
}

you can also use object notation to fill the array,
using object notation, you can provide the value (v:) and the formatted value (f:).

hAxis: {
  ticks: [{v: new Date(2018, 0, 1), f: '01/01/2018'}, {v: new Date(2018, 1, 1), f: '02/01/2018'}, ...]
}

see following working snippet, the data and ticks are built dynamically...

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

function drawChart() {
  var datePattern = 'MM/dd/yyyy';
  var formatDate = new google.visualization.DateFormat({
    pattern: datePattern
  });

  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('date', 'X');
  dataTable.addColumn('number', 'Value');

  var oneDay = (1000 * 60 * 60 * 24);
  var startDate = new Date(2018, 0, 1);
  var endDate = new Date(2018, 9, 0);
  var ticksAxisH = [];
  for (var i = startDate.getTime(); i <= endDate.getTime(); i = i + oneDay) {
    // set x value
    var rowDate = new Date(i);
    var xValue = {
      v: rowDate,
      f: formatDate.formatValue(rowDate)
    };

    // add tick at beginning of each month
    if (rowDate.getDate() === 1) {
      ticksAxisH.push(xValue);
    }

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

    // add data row
    dataTable.addRow([
      xValue,
      yValue
    ]);
  }

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.LineChart(container);
  chart.draw(dataTable, {
    chartArea: {
      height: '100%',
      width: '100%',
      top: 32,
      left: 48,
      right: 18,
      bottom: 32
    },
    hAxis: {
      ticks: ticksAxisH
    },
    height: 288,
    legend: {
      position: 'top'
    },
    width: '100%'
  });
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>