根据价值改变步长区域颜色

时间:2015-09-18 23:09:41

标签: javascript charts chart.js canvasjs

我正在使用CanvasJS和ChartJS,并且想知道是否可以根据点值获得不同颜色的区域?我正在从休息api填充图表

这是我的javascript:

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: '/getdata',
        success: function (response) {
            var json = $.parseJSON(response);
            var containter = document.getElementById("chart");

            var data = [];

            json.forEach(function(item){
                var date = new Date(item.time);
                    date = ("00" + date.getHours()).slice(-2) + ":" +
                        ("00" + date.getMinutes()).slice(-2) + ":" +
                        ("00" + date.getSeconds()).slice(-2) + "." +
                        ("00" + date.getMilliseconds()).slice(-3);

                var obj = {
                    y : item.price,
                    label : date
                };

                data.push(obj);
            });

            var chart = new CanvasJS.Chart(containter,{
                axisY: {
                    title: "Price"
                },
                axisX: {
                    labelAngle: -45
                },
                data: [
                    {
                        type: "stepArea",
                        dataPoints: data
                    }
                ]
            });

            chart.render();

        }
    });

所以在这个例子中我想如果价格在4.00到7.99范围内有绿色区域颜色,如果价格是8.00到11.99有黄色而如果高于12有红色。

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以扩展Chart.js条形图(〜步区域图)来执行此操作,如此

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

        this.datasets
            .filter(function (dataset) {
                // only do this for the arrays
                return typeof (dataset.fillColor) === "object";
            })
            .forEach(function (dataset) {
                dataset.bars.forEach(function (bar) {
                    dataset.fillColor.forEach(function (range) {
                        if (bar.value >= (range.from || -Infinity) && bar.value < (range.to || Infinity))
                            // set the bar color, the tooltip hover color and the cached (used to restore after a tooltip hover) color based on the value
                            bar.fillColor = bar.highlightFill = bar._saved.fillColor = range.fillColor;
                    })
                })
            })
    }
});

其中图表数据有fillColor的数组(而不是字符串),如此

datasets: [
    {
        ...
        // sorted range with colors
        fillColor: [
            { to: 50, fillColor: "rgba(220,220,220,0.2)" },
            { from: 50, to: 75, fillColor: "rgba(220,0,0,0.2)" },
            { from: 75, to: 100, fillColor: "rgba(0,0,220,0.5)" },
            { from: 100, fillColor: "rgba(0,0,220,0.2)" },
        ],
        ...

请务必使用BarAlt而不是Bar

来调用图表

小提琴 - https://jsfiddle.net/hhybyhfw/

enter image description here

相关问题