javascript chart.js 图表上的叠加线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28076525/
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-10-28 08:22:27  来源:igfitidea点击:

Overlay Line on chart.js Graph

javascriptchart.js

提问by LaurenceHerbert

I was wondering if it was possible to overlay a line ontop of a chart.js graph, such as a line graph ? For example, on the x axis a horizontal line would be drawn at value 20 across the graph

我想知道是否可以在 chart.js 图形(例如折线图)上叠加一条线?例如,在 x 轴上,将在图形上以值 20 绘制一条水平线

采纳答案by Quince

I've created something called an overlay chart that i have added to my fork of chart.js (https://github.com/leighquince/Chart.js) that could be used in this situation. it works in the same was as a line or bar chart, only difference is you declare an extra property called typethat can either be 'line'or 'bar'. Then just call new Chart(ctx).Overlay(data).

我创建了一个叫做叠加图表的东西,我已经将它添加到我的 chart.js ( https://github.com/leighquince/Chart.js) 的分支中,可以在这种情况下使用。它工作在同是作为一条线或条形图,唯一的区别是你声明了一个额外的属性type,它们可以是'line''bar'。然后只需调用new Chart(ctx).Overlay(data).

So for your example you could just have your bar chart and then provided another data set (with some better colors than i have used) to show the line.

因此,对于您的示例,您可以只使用条形图,然后提供另一个数据集(使用比我使用的颜色更好的颜色)来显示线条。

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "My First dataset",
    //new option, barline will default to bar as that what is used to create the scale
    type: "line",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(0,0,0,0.6)",
    pointColor: "rgba(0,0,0,0.6)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    datasetFill:false,
    data: [20, 20, 20, 20, 20, 20, 20]
  }, {
    label: "My First dataset",
    //new option, barline will default to bar as that what is used to create the scale
    type: "bar",
    fillColor: "rgba(220,20,220,0.2)",
    strokeColor: "rgba(220,20,220,1)",
    pointColor: "rgba(220,20,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [32, 25, 33, 88, 12, 92, 33]
  }]
};
var ctx = document.getElementById("canvas").getContext("2d");
var chart = new Chart(ctx).Overlay(data, {
  responsive: false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githack.com/leighquince/Chart.js/master/Chart.js"></script>

<canvas id="canvas" width="400"></canvas>

回答by StrangeWill

I needed something similar, but instead of a line graphI needed like a real overlay line that was flat.

我需要类似的东西,但我需要的不是折线,而是一条真正平坦的叠加线。

Just extended the chart like so:

像这样扩展图表:

    Chart.types.Bar.extend({
        name: 'BarOverlay',
        draw: function (ease) {
            Chart.types.Bar.prototype.draw.apply(this);
            ctx.beginPath();
            ctx.lineWidth = 2;
            ctx.strokeStyle = 'rgba(255, 0, 0, 1.0)';
            ctx.moveTo(35, this.scale.calculateY(100));
            ctx.lineTo(this.scale.calculateX(this.datasets[0].bars.length), this.scale.calculateY(100));
            ctx.stroke();
        }
    });

Mine is hard-coded to draw a line at the "100" mark (in this case, where we were looking at having a target of 100%).

我的被​​硬编码为在“100”标记处画一条线(在这种情况下,我们正在寻找 100% 的目标)。

And call it like so:

并像这样称呼它:

new Chart(ctx).BarOverlay(data, options);

I also found Quince's code out of date and not compatible with the 1.0.2 Chart.js code somehow (rendering went all sideways).

我还发现 Quince 的代码已经过时,并且以某种方式与 1.0.2 Chart.js 代码不兼容(渲染完全横向)。

回答by christutty

StrangeWill's answer was excellent as a foundation but I needed data-driven vertical lines on a bar graph so modified it as follows:

StrangeWill 的答案作为基础非常好,但我需要条形图上的数据驱动垂直线,因此对其进行了如下修改:

First I added a property to the options array (adding another dataset is perhaps cleaner but I would have had to tell ChartJS to ignore it), where each option is a data value index that I want to highlight, roughly as follows:

首先,我向 options 数组添加了一个属性(添加另一个数据集可能更清晰,但我不得不告诉 ChartJS 忽略它),其中每个选项都是我要突出显示的数据值索引,大致如下:

ChartDefaults.verticalOverlayAtBar = [itemOne, itemTwo]
...
var HistoryChart = new Chart(ctx).BarOverlay(ChartData, ChartDefaults);

I then modified StrangeWill's code, extending it to iterate the array of items from above and draw vertical lines on the indicated bar.

然后我修改了 StrangeWill 的代码,扩展它以从上方迭代项目数组并在指示的条上绘制垂直线。

Chart.types.Bar.extend({
    name: 'BarOverlay',
    draw: function (ease) {

        // First draw the main chart
        Chart.types.Bar.prototype.draw.apply(this);

        var ctx = this.chart.ctx;
        var barWidth = this.scale.calculateBarWidth(this.datasets.length);

        for (var i = 0; i < this.options.verticalOverlayAtBar.length; ++i) {

            var overlayBar = this.options.verticalOverlayAtBar[i];

            // I'm hard-coding this to only work with the first dataset, and using a Y value that I know is maximum
            var x = this.scale.calculateBarX(this.datasets.length, 0, overlayBar);
            var y = this.scale.calculateY(2000);

            var bar_base = this.scale.endPoint

            ctx.beginPath();
            ctx.lineWidth = 2;
            ctx.strokeStyle = 'rgba(255, 0, 0, 1.0)';
            ctx.moveTo(x, bar_base);
            ctx.lineTo(x, y);
            ctx.stroke();
        }
        ctx.closePath();
    }
});

It's not perfect as I'm not familiar with the internals ChartJs code, in particular my lines were 2 bars off although my suspicion is that that's a fencepost error in the data array rather than the chart calculations. However, hopefully it's a useful step forwards for someone else.

这并不完美,因为我不熟悉 ChartJs 的内部代码,特别是我的线条有 2 个小节,尽管我怀疑这是数据数组中的围栏错误,而不是图表计算。但是,希望这是对其他人有用的一步。