ChartJS - 突出显示分组条形图

时间:2015-05-10 07:37:38

标签: jquery chart.js

我有一个包含以下数据结构的表:

if ($("#demo-bar-chart").length) {  
var gpdData = {
"labels": ["2013", "2014", "2015", "2016"],
"datasets": [
    {
        "label": "China",
        "fillColor": "rgba(220,220,220,0.5)",
        "strokeColor": "rgba(220,220,220,0.8)",
        "highlightFill": "rgba(220,220,220,0.75)",
        "highlightStroke": "rgba(220,220,220,1)",
        "data": [0.5,11,2,3]
    },
    {
        "label": "India",
        "fillColor": "rgba(151,187,205,0.5)",
        "strokeColor": "rgba(151,187,205,0.8)",
        "highlightFill": "rgba(151,187,205,0.75)",
        "highlightStroke": "rgba(151,187,205,1)",
         "data": [1,9,4,6]
    }  
]
}

2016年的数字是预测的数字,我想强调COLUMN不是每个酒吧。将它们分组并显示视觉分离。虽然我似乎无法在API中找到任何内容来启用列背景颜色。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以扩展条形图以在列上绘制突出显示。最好从突出显示您可以传入的选项开始(下面代码中的highlightFromIndex)

HTML

<canvas id="myChart" width="400" height="200"></canvas>

JS

Chart.types.Bar.extend({
    name: "BarAlt",
    draw: function () {
        Chart.types.Bar.prototype.draw.apply(this, arguments);

        // overlay the highlight
        var ctx = this.chart.ctx;
        var scale = this.scale;
        var xColumnWidth = (scale.width - scale.xScalePaddingLeft - scale.xScalePaddingRight) / scale.xLabels.length
        ctx.fillStyle = 'rgba(255, 0, 0, 0.1)'
        ctx.fillRect(
            scale.xScalePaddingLeft + xColumnWidth * this.options.highlightFromIndex,
            scale.startPoint,
            xColumnWidth * (scale.xLabels.length - this.options.highlightFromIndex + 1),
            scale.endPoint - scale.startPoint)
    }
});


var ctx = $("#myChart").get(0).getContext("2d");

var gpdData = {
    "labels": ["2013", "2014", "2015", "2016"],
    "datasets": [
        {
            "label": "China",
            "fillColor": "rgba(220,220,220,0.5)",
            "strokeColor": "rgba(220,220,220,0.8)",
            "highlightFill": "rgba(220,220,220,0.75)",
            "highlightStroke": "rgba(220,220,220,1)",
            "data": [0.5, 11, 2, 3]
        },
        {
            "label": "India",
            "fillColor": "rgba(151,187,205,0.5)",
            "strokeColor": "rgba(151,187,205,0.8)",
            "highlightFill": "rgba(151,187,205,0.75)",
            "highlightStroke": "rgba(151,187,205,1)",
            "data": [1, 9, 4, 6]
        }
    ]
}

var myBarChart = new Chart(ctx).BarAlt(gpdData, {
    highlightFromIndex: 3
});

小提琴 - http://jsfiddle.net/smLcr3v4/