Search code examples
javascriptgoogle-visualization

How can I set the lower bound on the x axis for a google chart?


I'm trying set the x range on a date based google bar chart. I'd like the year of the chart to start at January 1, even though the data doesn't start until April.

I've seen a number of suggestions for how to set the min and max vertical range, but I could not make them work on the x axis. I don't know if the issue is the x-axis, or the fact that I'm using dates as my x axis. I do get this error when I try to set a min

"a.getTime is not a function"

Here's my working code, with no limits:

var data = new google.visualization.DataTable();
data.addColumn("date", "Season Start Date")
data.addColumn("number", "Acres Burned")
var options = {
    "title": "US Fire data TBD!!!",
    "hAxis": {
        "title": "Year"
    },
    "vAxis": {
        "title": "Total Acres Burned"
    }
}
data.addRows([
[new Date(2021, 5, 12), 1000],
[new Date(2021, 5, 14), 400],
[new Date(2021, 5, 15), 0],
[new Date(2021, 5, 16), -39],
[new Date(2021, 5, 17), 165],
[new Date(2021, 5, 18), 0],
[new Date(2021, 5, 19), 1000],
[new Date(2021, 5, 20), 1000],
]);
var chart = new google.visualization.ColumnChart(document.getElementById("us_chart"))
chart.draw(data, options);

This code renders the error message ("a.getTime is not a function"), instead of the chart:

var options = {
    "title": "US Fire data TBD!!!",
    "hAxis": {
        "title": "Year",
        "viewWindowMode":"explicit",
        "viewWindow": {
          "min": "new Date(2021, 5, 1)",
          "max": "new Date(2021, 8, 1)"
        }

    },
    "vAxis": {
        "title": "Total Acres Burned"
    }
}

Any ideas?

Thanks!


Solution

  • the min / max values for the axis should be dates, not strings.

    var options = {
        "title": "US Fire data TBD!!!",
        "hAxis": {
            "title": "Year",
            "viewWindow": {
              "min": new Date(2021, 5, 1),
              "max": new Date(2021, 8, 1)
            }
    
        },
        "vAxis": {
            "title": "Total Acres Burned"
        }
    }  
    

    and the following option isn't necessary...

    "viewWindowMode":"explicit",