knotito
knotito

Reputation: 1392

Is it possible to set dates as min/max values for google line charts?

Is it possible to set dates as min/max values for google line charts?

Here is some sample code that demonstrates the problem:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
        title: 'Company Performance',
        hAxis: {viewWindow: {min: new Date(2005,1,1)}}
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
<div id="chart_div"></div>

Maybe the problem is on the line:

hAxis: {viewWindow: {min: new Date(2005,1,1)}}

Upvotes: 1

Views: 2705

Answers (1)

asgallant
asgallant

Reputation: 26340

Your x-axis data are not Date objects, which is why setting the hAxis.viewWindow.min option to 'new Date(2005, 1, 1)` doesn't work. If you switch the domain column to a "date" type, it will work:

var data = new google.visualization.DataTable();
data.addColumn('date', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
    [new Date(2004, 0, 1), 1000, 400],
    [new Date(2005, 0, 1), 1170, 460],
    [new Date(2006, 0, 1), 660, 1120],
    [new Date(2007, 0, 1), 1030, 540]
]);

If your data is just years (and not related to any specific day of the year), then it might be best to use a "number" type column instead:

var data = new google.visualization.DataTable();
data.addColumn('number', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
    [2004, 1000, 400],
    [2005, 1170, 460],
    [2006, 660, 1120],
    [2007, 1030, 540]
]);

and set the hAxis.viewWindow.min option to a number:

hAxis: {viewWindow: {min: 2005}}

Upvotes: 3

Related Questions