【问题标题】:Highcharts Plotoptions SeriesHighcharts Plotoptions 系列
【发布时间】:2013-08-08 14:18:00
【问题描述】:

我目前在我的网站中使用 Highcharts。在我的一个图表(基本柱形图)中,我有多个系列,我可以单击底部显示的名称来显示/隐藏。

我可以有很多系列,我想同时将系列的数量限制为 3 个。这意味着当它加载图表时,它只显示 3 个系列,其他系列不显示。如果我点击第 4 个系列,原来存在的 3 个系列中的一个将消失,因此活动系列的数量始终保持为 3。

我一直在寻找它,我发现我需要在 plotOptions.series 字段中进行一些修改,我深入研究了 Highcharts API 参考,但没有找到我想要的。我对代码的第一次尝试是这样的:

$('#container').highcharts({
    plotOptions:{
        series: {
            var series = this.series;
            var nb_of_visible_series = 0;              

            //Here i count the number of visible series
            for(var i=0; i<series.length; i++) {
              if(series[i].visible) {
                  nb_of_visible_series++:
              }
            }

            //If too many series are visible I'll randomly 
            //hide as many series as necessary
            if(nb_of_visible_series>3) {
                var nb_of_series_to_hide = nb_of_visible_series-3;
                while(nb_of_series_to_hide>0) {
                    var i=Math.floor(Math.random()*series.length);
                    if(series[i].visible) {
                        series[i].hide()
                        nb_of_series_to_hide--;
                    }
                }
            }
        }
    }
}

所以这就是想法,但我不知道将它放在哪里真实(不是直接在plotOptions.series 字段中,就像我猜的那样?)。我可以把它放在plotOptions.series.events.legentItemClick 但是在加载图表时它不会被考虑在内。

我正在寻找有关我的代码的一些跟踪和建议(我是 JS 初学者),并在此先感谢您。对不起,我的英语很差。

【问题讨论】:

    标签: javascript highcharts series


    【解决方案1】:

    肯定你写的代码不会工作。 Highcharts 的选项应该是 javascript 对象,而不是变量、选项等之间混合的东西。

    1) 要在 init 上只显示三个系列的预处理数据,如下所示:

    var series = [{ data: [..], name: 'name 1' ..} , { data: [..], name: 'name 2' ..} , ... , {data: [..], name: 'name n'}];
    
    for (var i = 0, len = series.length; i < len; i++) {
        series[i].visible = i < 3; //setup variable series.visible to show/hide on init load.
    }
    
    $('#container').highcharts({
        series: series //pass variable with updated visible option
    });
    

    2) 正如您所注意到的,您需要为legendItemClick 编写自己的函数,该函数将检查有多少系列可见(循环通过chart.series 并计数series.visible == true)。然后使用series.hide() / series.show()隐藏/显示特定系列。

    【讨论】:

    • 最好处理每个系列的事件显示而不是 legendItemClick,因为您可以希望通过 show() 和 hide() 方法动态控制可见性,因此不会触发 legendItemClick 处理程序。跨度>
    • 问题没有提到任何关于使用hide()show() 方法的内容。随时添加您的答案,支持hide()show()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多