如何使用Highcharts创建单个系列条形图

jwe*_*rre 1 highcharts

我正在尝试创建一个带有单个系列和图例中多个标签的简单Highcharts条形图。怎么做?

这是一个例子:

    $('#container').highcharts({

    chart: {
        type: 'bar',
    },
    legend: {
        enabled: true,
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        labelFormatter: function() {
            return this.name + " - <span class='total'>"+this.y+"</span>"
        }
    },
    title: {
        text: 'Simple Bar Graph'
    },
    xAxis: {
        categories: ['First', 'Second', 'Third', 'Fourth', , 'Fifth'],
        allowDecimals: false
    },
    yAxis: {
        allowDecimals: false
    },

    series: [
        {
            data: [
                {y: 6, name: 'First', color: 'blue'},
                {y: 7, name: 'Second', color: 'green'},
                {y: 9, name: 'Third', color: 'yellow'},
                {y: 1, name: 'Fourth', color: 'orange'},
                {y: 1, name: 'Fifth', color: 'red'}
            ]
        }
    ],

});
Run Code Online (Sandbox Code Playgroud)

Mor*_*osh 5

幸运的是,Highcharts非常灵活。我们可以做一些技巧(也许是骇客?)来实现这种“非常规”任务。

在这种情况下,您可以做的是创建“假”系列,并使用自定义事件处理程序:

    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'}

    ],
Run Code Online (Sandbox Code Playgroud)

为了格式化图例标签,我们可以使用labelFormatter图例:

    legend: {
        labelFormatter: function(){
            return names[this.index-1];
        }
    },
Run Code Online (Sandbox Code Playgroud)

这会将图例标签设置为相应点的名称。

最后,我们需要处理图例点击,以模仿“正常”行为:

    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});
                }
            }
        }
    },
Run Code Online (Sandbox Code Playgroud)

这些仅是示例,您显然可以改善此情况并适应自己的需要。

祝好运!

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

  • 谢谢@MorKadosh。但是为什么你说这是不合常规的。看来这将是显示此数据的最基本方法。您是否觉得有更好的方法来显示类似上面的数据? (2认同)