Google Charts: How to keep options the same with d

2019-09-07 09:39发布

问题:

I've used the following code http://jsfiddle.net/asgallant/WaUu2/ which allows me to toggle on and off series from my combo chart. The issue I was having with it, is my combo chart used both line and bar series types. When I toggled series from the chart on and off I would lose my series type setting. I put together the following to keep my average column as a line chart and the rest as a bar chart.

function setChartView() {
    var state = columnFilter.getState();
    var row;
    var view = {
        columns: [0],
    };
    var labels = [];
    for (var i = 0; i < state.selectedValues.length; i++) {
        row = columnsTable.getFilteredRows([{
            column: 1,
            value: state.selectedValues[i]
        }])[0];
        view.columns.push(columnsTable.getValue(row, 0));
        labels.push([columnsTable.getValue(row, 0), columnsTable.getValue(row, 1)]);
    }
    // sort the indices into their original order
    labels.sort(function(a, b) {
        return (a[0] - b[0]);
    });
    view.columns.sort(function(a, b) {
        return (a - b);
    });

    chart.setView(view);

    for (var i = 0; i < labels.length; i++) {
        chart.setOption('series.' + i + '.type', 'bars');
        if (labels[i][1] == 'Average') {
            chart.getOptions().series[i].type = 'line';
        }
    }

    chart.draw();
}

google.visualization.events.addListener(columnFilter, 'statechange', setChartView);

setChartView();
columnFilter.draw();

It appears to be working for my specific case, however, what if I wanted to keep all of my options the same?

回答1:

Try changing this:

                  for(var i = 0; i < view.columns.length; i++){
                        var col = view.columns[i]
                        chart.setOption('series.' + col + '.type', 'bars');
                        if(col == yourAverageColumnOriginalIndex){
                            chart.getOptions().series[col].type = 'line';
                        }
                    }