You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击图例隐藏Google Chart数据系列后,日期筛选失效的问题求助

解决Google Chart日期滑块切换后隐藏系列重新显示的问题

当前代码的问题在于:使用日期滑块调整范围时,Dashboard会重置图表的数据源和配置,导致之前通过DataView隐藏的系列被恢复,仅设置灰色无法实现完全隐藏。以下是修复后的代码及关键说明:

修复后完整代码

google.charts.load('current', {packages: ['controls']}).then(initialize);

function initialize() {
  var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1001YnF8LCwKyzpS4pgmZnwFVigL-LlnqwWn6xjnso2k/edit#gid=0&range=A:BT');
  query.send(drawDashboard);
}

function drawDashboard(response) {
  var data = response.getDataTable();
  var formatMS = new google.visualization.NumberFormat({pattern: '# mm'});
  for (var colIndex = 1; colIndex < data.getNumberOfColumns(); colIndex++) {
    formatMS.format(data, colIndex);
  }
  var dataView = new google.visualization.DataView(data);
  dataView.setColumns([0,1,2,{sourceColumn: 3, role: 'interval'}, {sourceColumn: 4, role: 'interval'}, 5,{sourceColumn: 6, 'type': 'string', role: 'tooltip', 'p': {'html': true}},7,8,9,10,11,12,13,14,15,{sourceColumn: 16, role: 'interval'}, {sourceColumn: 17, role: 'interval'}, 18,{sourceColumn: 19, 'type': 'string', role: 'tooltip', 'p': {'html': true}},20,21,22,23,24,25,26,27,28,{sourceColumn: 29, role: 'interval'}, {sourceColumn: 30, role: 'interval'},31,{sourceColumn: 32, 'type': 'string', role: 'tooltip', 'p': {'html': true}},33,34,35,36,37,38,39,40,41,{sourceColumn: 42, role: 'interval'}, {sourceColumn: 43, role: 'interval'}, 44,{sourceColumn: 45, 'type': 'string', role: 'tooltip', 'p': {'html': true}},46,47,48,49,50,51,52,53,54,{sourceColumn: 55, role: 'interval'}, {sourceColumn: 56, role: 'interval'}, 57,{sourceColumn: 58, 'type': 'string', role: 'tooltip', 'p': {'html': true}},59,60,61,62,63,64,65,66,67,68,69,70,71]);
  var viewColumns = [0,7,20,33,46,59,66,67,68,69,70,71];

  var YearPicker = new google.visualization.ControlWrapper({
    controlType: 'NumberRangeFilter',
    containerId: 'filter_div',
    options: {
      maxValue: 2150,
      minValue: 1891,
      filterColumnLabel: 'Year',
      ui: {
        cssClass: 'filter-date',
        format: {pattern: '0000'},
        labelStacking: 'vertical',
        allowTyping: true,
        allowMultiple: false
      }
    },
    state: {lowValue: 1891, highValue: 2150},
  });

  google.visualization.events.addListener(YearPicker, 'statechange', function () {
    var state = YearPicker.getState();
    state.lowValue = Math.min(2021, state.lowValue);
    YearPicker.setState({
      lowValue: state.lowValue,
      highValue: state.highValue
    });
    YearPicker.draw();
  });

  var series = {
    0: {color:'navy', visibleInLegend: true}, //Auckland
    1: {color:'green', visibleInLegend: true }, //Taranaki
    2: {color:'gold', visibleInLegend: true}, //Wellington
    3: {color:'red', visibleInLegend: true}, //Lyttelton
    4: {color:'DeepSkyBlue', visibleInLegend: true}, //Dunedin
    5: {color:'#47d045', visibleInLegend: true}, //NZ RCP2.6 M
    6: {color:'#0e038d', visibleInLegend: true}, //NZ RCP4.5 M
    7: {color:'#b8bb62', visibleInLegend: true}, //NZ RCP8.5 M
    8: {color:'#b22123', visibleInLegend: true}, //NZ RCP8.5 H
    9: {color:'blue', visibleInLegend: true}, //NZ Mean
    10: {color:'blue', visibleInLegend: false}, //NZ Mean
  };

  var seriesColors = {};
  for (var column in series) {
    if (series.hasOwnProperty(column)) {
      seriesColors[column] = series[column].color;
    }
  }

  var MSLChart = new google.visualization.ChartWrapper({
    chartType: 'LineChart',
    containerId: 'chart_div',
    dataTable: dataView,
    options: {
      fontSize: '20',
      title: 'NZ Annual Relative Mean Sea Level Summary',
      hAxis: {title: 'Year', format: '0000'},
      vAxis: {title: 'Height above 1986-2005 IPCC Baseline (mm)', format:'###0'},
      height: 600,
      chartArea: {height: '81%', width: '85%', left: 100},
      legend: {position: 'top', maxLines: 5, alignment: 'start', textStyle: {fontSize: 9}},
      colors: ['blue'],
      tooltip: {
        isHtml: true
      },
      trendlines: {
        9: {
          type: 'linear',
          color: 'black',
          visibleInLegend: true,
          showR2: true,
        },
        10: {
          type: 'polynomial',
          color: 'purple',
          degree: 2,
          visibleInLegend: true,
          showR2: true,
        },
      },
      series: series,
      intervals: { 'style':'bars','color': '#6292dc' },
      interpolateNulls: 'True',
    },
    view: {columns: viewColumns}
  });

  // 记录被隐藏的系列索引(对应viewColumns中的列位置,从1开始)
  var hiddenSeries = [];
  var columns = [];
  for (var i = 0; i < dataView.getNumberOfColumns(); i++) {
    columns.push(i);
  }

  // 应用隐藏状态到DataView和图表配置
  function applyHiddenState() {
    var currentView = MSLChart.getDataView() || dataView;
    var newColumns = [...columns];
    hiddenSeries.forEach(function(seriesIdx) {
      var col = viewColumns[seriesIdx];
      newColumns[col] = {
        label: dataView.getColumnLabel(col),
        type: dataView.getColumnType(col),
        calc: function () {
          return null;
        }
      };
      series[seriesIdx - 1].color = '#CCCCCC';
    });
    // 恢复未隐藏系列的颜色
    for (var idx = 1; idx < viewColumns.length; idx++) {
      if (!hiddenSeries.includes(idx)) {
        series[idx - 1].color = seriesColors[idx - 1];
      }
    }
    var view = new google.visualization.DataView(currentView);
    view.setColumns(newColumns);
    MSLChart.setDataTable(view);
    MSLChart.setOption('series', series);
    MSLChart.draw();
  }

  google.visualization.events.addListener(MSLChart, 'select', function () {
    var chartArea = MSLChart.getChart().getChartLayoutInterface().getChartAreaBoundingBox();
    var vAxisTop = MSLChart.getChart().getChartLayoutInterface().getVAxisValue(chartArea.top);
    var vAxisBtm = MSLChart.getChart().getChartLayoutInterface().getVAxisValue(chartArea.top + chartArea.height);

    var sel = MSLChart.getChart().getSelection();
    if (sel.length > 0 && sel[0].row === null && sel[0].column > 0) {
      var seriesIdx = sel[0].column;
      var col = viewColumns[seriesIdx];
      if (columns[col] === col) {
        // 隐藏系列
        hiddenSeries.push(seriesIdx);
      } else {
        // 显示系列
        hiddenSeries = hiddenSeries.filter(idx => idx !== seriesIdx);
        columns[col] = col;
      }
      applyHiddenState();
      // 保持Y轴范围不变
      MSLChart.setOption('vAxis.viewWindow.max', vAxisTop);
      MSLChart.setOption('vAxis.viewWindow.min', vAxisBtm);
      MSLChart.draw();
    }
  });

  var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div')).bind(YearPicker, MSLChart);
  
  // 监听Dashboard就绪事件,每次绘制后应用隐藏状态
  google.visualization.events.addListener(dashboard, 'ready', function() {
    applyHiddenState();
  });
  
  dashboard.draw(dataView);
}

关键修改说明

  1. 新增hiddenSeries数组:持久化存储被用户隐藏的系列索引,避免过滤器更新时丢失状态。
  2. 封装applyHiddenState函数:统一处理隐藏状态的应用逻辑,包括修改DataView列定义和系列颜色,确保每次图表绘制时都能同步状态。
  3. 监听Dashboard的ready事件:在过滤器触发图表更新后,自动重新应用隐藏状态,保证隐藏的系列不会重新显示。
  4. 优化图例点击逻辑:通过操作hiddenSeries数组来管理系列的显示/隐藏状态,替代直接修改columns数组的临时方式。

内容的提问来源于stack exchange,提问作者Bryan Ward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:20:36