google-visualizationgchart

Google Charts Filter/Control chart based on hidden value


I have a scattor plot with the following data:

[ 'HDD', 'Oil Consumption']
['100','1000']
['50','500']
['10,'100']

Say each data point is taken from a specific date:

[ 'HDD', 'Oil Consumption', 'Date']
['100','1000','1 January 2015']
['50','500', '1 February 2015']
['10,'100', '1 March 2015']

How can I add a filter (DateRangeFilter preferably) to filter based on the date column, even though the date column isn't really apart of the scatter plot.


Solution

  • You do this with ChartWrapper, ControlWrapper and a Dashboard.

    Here is the documentation related to this from Google.

    Basically, you instead of initiating a chart with new google.visualization.ScatterChart(document.getElementById('yourId')) you use something called ChartWrapper (which is, in my opinion, an easier and more readable way of doing this).

    Then you create a ControlWrapper (a wrapper for your control (date range filter) element).

    Lastly you bind your ControlWrapper to your ChartWrapper via your Dashboard. Your data could be like:

            var data = google.visualization.arrayToDataTable([
          ['Age', 'Weight', 'Date'],
          [ 8,      12, new Date(2015, 10, 1)],
          [ 4,      5.5, new Date(2015, 10, 2)],
          [ 11,     14, new Date(2015, 10, 3)],
          [ 4,      5, new Date(2015, 10, 4)],
          [ 3,      3.5, new Date(2015, 10, 5)],
          [ 6.5,    7, new Date(2015, 10, 6)]
        ]);
    

    A ChartWrapper could look like this:

    var scatterWrap = new google.visualization.ChartWrapper({
            chartType:'ScatterChart',
            containerId:'chart_div',
            dataTable:data,
            view:{
                columns:[0, 1] // This makes sure your ScatterChart won't try to use the third column for visualization, that would result in an error.
            }
        });
    

    and a ControlWrapper like this

    var dateRangeWrap = new google.visualization.ControlWrapper({
            controlType:'DateRangeFilter',
            containerId:'dateRange',
            options:{
                filterColumnIndex:2
            }
        });
    

    Finally initializing and binding to your Dashboard:

          var googleDashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
          googleDashboard.bind(dateRangeWrap, scatterWrap);
          googleDashboard.draw(data);
    

    This would all end in this Fiddle. (Note that you need to load controls instead of corechart in your google.load).