1
votes

Here is a chart rendered using one of the Google Charts demos. My actual use case is very similar to this, a vertical axis with integer labels and a horizontal axis with string labels.

Fiddle: https://jsfiddle.net/1f0dvehq/

Gchart demo

The X-axis has the labels starting at what seems to be an arbitrary distance from 0,0. I need those red and blue lines to start at X=0, and have the first X-axis label shift so that it sits below 0,0, as in the following screenshot:

proper alignment

I have tried passing minValue options to the horizontal axis via hAxis but this doesn't seem to work with strings like it does with integers.

The following options are being passed to the fiddle chart (again, from the demo code):

var options = {
  title: 'Company Performance',
  curveType: 'function',
  legend: { position: 'bottom' }
};

How can I align the X axis labels so they take up 100% of the chart width, with the first label falling underneath the Y axis itself? I would like to accomplish this from within the chart configuration itself if possible, rather than CSS or extraneous JS.

If anyone could also explain the logic of this setting it would be much appreciated. It strikes me as odd that it's the default setting, and from my experience with google frameworks they usually choose default values that adhere to a convention, but this seems nonsensical. I would expect the "2004" label to be left justified on the X-axis, and the intervals between the X labels to be evenly spaced with "2007" flush against the right edge of the chart.

1

1 Answers

1
votes

can't explain why, but this is default behavior for a discrete axis.

if you would like to display strings on the x-axis,
but still have the behavior of a continuous axis,
you can use the ticks option to format the axis labels.

using object notation, you can provide the value (v:) of each tick,
as well as the formatted value (f:)...

{v: 0, f: '2004'}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', 'Expenses'],
    [0, 1000, 400],
    [1, 1170, 460],
    [2, 660,  1120],
    [3, 1030, 540]
  ]);

  var options = {
    title: 'Company Performance',
    curveType: 'function',
    legend: {position: 'bottom'},
    hAxis: {
      ticks: [
        {v: 0, f: '2004'},
        {v: 1, f: '2005'},
        {v: 2, f: '2006'},
        {v: 3, f: '2007'}
      ]
    }
  };

  var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
  chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="curve_chart"></div>