How to create a single series bar graph with Highcharts

前端 未结 2 1006
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 04:14

I\'m trying to create a simple Highcharts bar graph with a single series and multiple labels in the legend. How is this done?

Here is an example:

           


        
2条回答
  •  -上瘾入骨i
    2021-01-16 04:32

    Luckily, Highcharts is pretty flexible. We can do some tricks (maybe hacks?) to achieve this kind of "non-convential" tasks.

    What you could do in your case is create "fake" serieses, and use custom event handlers:

        series: [
            {
                pointWidth:20,
                color: colors[0],
                showInLegend:false,
                data: [
                    {y: 6, name: 'First', color: colors[0]},
                    {y: 7, name: 'Second', color: colors[1]},
                    {y: 9, name: 'Third', color: colors[2]},
                    {y: 1, name: 'Fourth', color: colors[3]},
                    {y: 1, name: 'Fifth', color: colors[4]}
                ]
            },
            {color: 'blue'},
            {color: 'green'},
            {color: 'yellow'},
            {color: 'orange'},
            {color: 'red'}
    
        ],
    

    In order to format the legend labels we can use labelFormatter for the legend:

        legend: {
            labelFormatter: function(){
                return names[this.index-1];
            }
        },
    

    this will set the legend label to the name of the corresponding point.

    And finally we need to handle the legend click, to imitate the "normal" behaviour:

        plotOptions: {
            series: {
                events: {
                    legendItemClick: function (x) {
                        var i = this.index  - 1;
                        var series = this.chart.series[0];
                        var point = series.points[i];   
    
                        if(point.oldY == undefined)
                           point.oldY = point.y;
    
                        point.update({y: point.y != null ? null : point.oldY});
                    }
                }
            }
        },
    

    These are just examples, you can obviously improve this and adjust to your own need.

    Good Luck!

    http://jsfiddle.net/otm0oq2c/3/

提交回复
热议问题