Javascript Chart.js - 绘制水平线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31092489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:12:28  来源:igfitidea点击:

Chart.js - draw horizontal line

javascriptchart.js

提问by KRiSTiN

I would like to draw a horizontal line in a chart using Chart.js. But I'm not able to do it.

我想使用Chart.js在图表中绘制一条水平线。但我做不到。

I've read this question - Chart.js — drawing an arbitrary vertical line- but I can't transform the code for drawing horizontal linesnot vertical.

我读过这个问题 - Chart.js - 绘制任意垂直线- 但我无法转换用于绘制水平线而非垂直线的代码。

I hope you can help me (especially potatopeelings :)).

我希望你能帮助我(尤其是土豆皮:))。

采纳答案by jbman223

Here is the JavaScript code to draw a horizontal line.

这是绘制水平线的 JavaScript 代码。

var data = {
    labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
    datasets: [{
        data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
    }]
};

var ctx = document.getElementById("LineWithLine").getContext("2d");

Chart.types.Line.extend({
    name: "LineWithLine",
    initialize: function () {
        Chart.types.Line.prototype.initialize.apply(this, arguments);
    },
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        var point = this.datasets[0].points[this.options.lineAtIndex]
        var scale = this.scale
        console.log(this);

        // draw line
        this.chart.ctx.beginPath();
        this.chart.ctx.moveTo(scale.startPoint+12, point.y);
        this.chart.ctx.strokeStyle = '#ff0000';
        this.chart.ctx.lineTo(this.chart.width, point.y);
        this.chart.ctx.stroke();

        // write TODAY
        this.chart.ctx.textAlign = 'center';
        this.chart.ctx.fillText("TODAY", scale.startPoint + 35, point.y+10);
    }
});

new Chart(ctx).LineWithLine(data, {
    datasetFill : false,
    lineAtIndex: 2
});

http://jsfiddle.net/7a4hhzge/455/

http://jsfiddle.net/7a4hhzge/455/

This is based off of the code used to draw an arbitrary vertical line, it may not be perfect but you should be able to adjust it to fit your needs.

这是基于用于绘制任意垂直线的代码,它可能并不完美,但您应该能够对其进行调整以满足您的需要。

回答by Julien Ricard

Without any additional code, I managed to draw a line by adding a new entry as a dataset with these options :

没有任何额外的代码,我设法通过添加一个新条目作为具有以下选项的数据集来画一条线:

Just replace with the size of your dataset, and with the value that the line represents.

只需替换为数据集的大小,以及该线代表的值。

{
  data: Array.apply(null, new Array(<length>)).map(Number.prototype.valueOf, <value>),
  fill: false,
  radius: 0,
  backgroundColor: "rgba(0,0,0,0.1)"
}

The radius of 0 will somehow hide the dots and the fill: false will make it appear as a line.

半径为 0 会以某种方式隐藏点,而 fill: false 会使其显示为一条线。

回答by dFelinger

If you need many lines with certain Y value, try this code

如果您需要具有特定 Y 值的多行,请尝试使用此代码

var data = {
    labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
    datasets: [{
        data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
    }]
};

var ctx = document.getElementById("LineWithLine").getContext("2d");

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

        var lines = this.options.limitLines;

        for (var i = lines.length; --i >= 0;) {

            var xStart = Math.round(this.scale.xScalePaddingLeft);
            var linePositionY = this.scale.calculateY(lines[i].value);

            this.chart.ctx.fillStyle = lines[i].color ? lines[i].color : this.scale.textColor;
            this.chart.ctx.font = this.scale.font;
            this.chart.ctx.textAlign = "left";
            this.chart.ctx.textBaseline = "top";

            if (this.scale.showLabels && lines[i].label) {
                this.chart.ctx.fillText(lines[i].label, xStart + 5, linePositionY);
            }

            this.chart.ctx.lineWidth = this.scale.gridLineWidth;
            this.chart.ctx.strokeStyle = lines[i].color ? lines[i].color : this.scale.gridLineColor;

            if (this.scale.showHorizontalLines) {
                this.chart.ctx.beginPath();
                this.chart.ctx.moveTo(xStart, linePositionY);
                this.chart.ctx.lineTo(this.scale.width, linePositionY);
                this.chart.ctx.stroke();
                this.chart.ctx.closePath();
            }

            this.chart.ctx.lineWidth = this.lineWidth;
            this.chart.ctx.strokeStyle = this.lineColor;
            this.chart.ctx.beginPath();
            this.chart.ctx.moveTo(xStart - 5, linePositionY);
            this.chart.ctx.lineTo(xStart, linePositionY);
            this.chart.ctx.stroke();
            this.chart.ctx.closePath();
        }
    }
});

new Chart(ctx).LineWithLine(data, {
    datasetFill : false,
    limitLines: [
        {
            label: 'max',
            value: 17,
            color: 'rgba(255, 0, 0, .8)'
        },
        {
            label: 'min',
            value: 1
        },
        {
            value: 7,
            color: 'rgba(0, 255, 255, .8)'
        }
    ],
});

http://jsfiddle.net/vsh6tcfd/3/

http://jsfiddle.net/vsh6tcfd/3/

回答by Carlos Nu?ez Tomeo

Based on dFelinger message I made a new char type that draws an average line on the line chart. Here's the code, just copy and call a new chart with the new type called 'lineWithAverage' WORKS ONLY FOR CHARTJS 2

基于 dFelinger 消息,我创建了一个新的 char 类型,可以在折线图上绘制一条平均线。这是代码,只需复制并调用名为“lineWithAverage”的新类型的新图表,仅适用于 CHARTJS 2

    Chart.controllers.lineWithAverage = Chart.controllers.line.extend({
        initialize: function () {
            Chart.controllers.line.prototype.initialize.apply(this, arguments);
        },
        draw: function () {
            Chart.controllers.line.prototype.draw.apply(this, arguments);

            var scale = this.scale
            var sum = 0;
            this.getDataset().data.forEach(function(value) {
              sum = sum + value;
            });

            var average = sum / this.getDataset().data.length;

            var averageCoord = this.calculatePointY(average);

            // draw line
            this.chart.chart.canvas.ctx = this.chart.chart.canvas.getContext('2d');
            this.chart.chart.canvas.ctx.beginPath();
            this.chart.chart.canvas.ctx.moveTo(0, averageCoord);
            this.chart.chart.canvas.ctx.strokeStyle = '#979797';
            this.chart.chart.canvas.ctx.lineTo(this.chart.chart.width, averageCoord);
            this.chart.chart.canvas.ctx.stroke();
        }
    });