0

我正在使用 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 有一个红色。

这可能吗?

4

1 回答 1

0

您可以扩展 Chart.js 条形图(~ step area chart)来做到这一点,像这样

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/


在此处输入图像描述

于 2015-09-23T10:06:46.327 回答