Chart.js - 绘制任意垂直线

时间:2015-05-15 10:04:38

标签: javascript chart.js

如何使用Chart.js在轴上的特定点绘制垂直线?

特别是,我想绘制一条线来表示LineChart上的当前日期。这是图表的模型: http://i.stack.imgur.com/VQDWR.png

enter image description here

5 个答案:

答案 0 :(得分:74)

更新 - 这个答案适用于Chart.js 1.x,如果您正在寻找2.x答案,请查看评论和其他答案。

您可以扩展折线图并包含用于在绘图函数中绘制线条的逻辑。

预览

enter image description here

<强> HTML

<div>
    <canvas id="LineWithLine" width="600" height="400"></canvas>
</div>

<强>脚本

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 point = this.datasets[0].points[this.options.lineAtIndex]
        var scale = this.scale

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

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

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

选项属性lineAtIndex控制在哪一点画线。

小提琴 - http://jsfiddle.net/dbyze2ga/14/

答案 1 :(得分:38)

分享我对chartjs.org 2.5版的解决方案。我想使用插件,以使实现可重用。

&#13;
&#13;
const verticalLinePlugin = {
  getLinePosition: function (chart, pointIndex) {
      const meta = chart.getDatasetMeta(0); // first dataset is used to discover X coordinate of a point
      const data = meta.data;
      return data[pointIndex]._model.x;
  },
  renderVerticalLine: function (chartInstance, pointIndex) {
      const lineLeftOffset = this.getLinePosition(chartInstance, pointIndex);
      const scale = chartInstance.scales['y-axis-0'];
      const context = chartInstance.chart.ctx;

      // render vertical line
      context.beginPath();
      context.strokeStyle = '#ff0000';
      context.moveTo(lineLeftOffset, scale.top);
      context.lineTo(lineLeftOffset, scale.bottom);
      context.stroke();

      // write label
      context.fillStyle = "#ff0000";
      context.textAlign = 'center';
      context.fillText('MY TEXT', lineLeftOffset, (scale.bottom - scale.top) / 2 + scale.top);
  },

  afterDatasetsDraw: function (chart, easing) {
      if (chart.config.lineAtIndex) {
          chart.config.lineAtIndex.forEach(pointIndex => this.renderVerticalLine(chart, pointIndex));
      }
  }
  };

  Chart.plugins.register(verticalLinePlugin);
&#13;
&#13;
&#13;

用法很简单:

 new Chart(ctx, {
     type: 'line',
     data: data,
     label: 'Progress',
     options: options,
     lineAtIndex: [2,4,8],
 })

上面的代码在位置2,4和8处插入红色垂直线,在这些位置穿过第一个数据集的点。

答案 2 :(得分:5)

我不得不经历麻烦,弄清楚如何使用ChartJS 2.0做类似的事情,所以我想我会分享。

这是基于覆盖图表原型的新方法,如下所述:https://github.com/chartjs/Chart.js/issues/2321

var ctx = document.getElementById('income-chart');

var originalDraw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function (ease) {
    originalDraw.call(this, ease);

    var point = dataValues[vm.incomeCentile];
    var scale = this.chart.scales['x-axis-0'];

    // calculate the portion of the axis and multiply by total axis width
    var left = (point.x / scale.end * (scale.right - scale.left));
                
    // draw line
    this.chart.chart.ctx.beginPath();
    this.chart.chart.ctx.strokeStyle = '#ff0000';
    this.chart.chart.ctx.moveTo(scale.left + left, 0);
    this.chart.chart.ctx.lineTo(scale.left + left, 1000000);
    this.chart.chart.ctx.stroke();

    // write label
    this.chart.chart.ctx.textAlign = 'center';
    this.chart.chart.ctx.fillText('YOU', scale.left + left, 200);
};

答案 3 :(得分:1)

我强烈建议您使用Chartjs-Plugin-Annotation

可以在CodePen

找到一个示例
var chartData = {
  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]
    }
  ]
};

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  new Chart(ctx, {
    type: "line",
    data: chartData,
    options: {
      annotation: {
        annotations: [
          {
            type: "line",
            mode: "vertical",
            scaleID: "x-axis-0",
            value: "MAR",
            borderColor: "red",
            label: {
              content: "TODAY",
              enabled: true,
              position: "top"
            }
          }
        ]
      }
    }
  });
};

请点击此处了解更多详情:https://stackoverflow.com/a/36431041

答案 4 :(得分:1)

这是一支笔,可以达到类似的效果,而无需使用chartjs-plugin-annotation或破解Chart.js的呈现方式或任何其他插件:https://codepen.io/gkemmey/pen/qBWZbYM

方法

  1. 使用组合条形图/折线图,然后使用条形图绘制垂直线。
  2. 使用两个y轴:一个用于条形图(我们不显示),另一个用于所有其他折线图数据集。
  3. 将条形图的y轴强制设置为min: 0max: 1。每当您想画一条垂直线时,都将{ x: where_the_line_goes, y: 1 }之类的数据对象添加到条形图数据集中。
  4. 笔还向条形图数据集和图例过滤器和标签回调添加了一些自定义数据,以从图例中排除条形图数据集,并控制垂直线上的标签。

优点

  1. 没有其他依赖项。没有自定义的猴子补丁/扩展。
  2. 注释插件似乎没有得到积极维护。例如,atm,其事件处理程序会引发有关“防止在被动事件上发生默认设置”的错误
  3. 也许是专业人士:注释插件始终显示绘制的线条的标签,并且您必须使用其事件回调来获得悬停显示效果。 Chart.js工具提示默认显示在悬停上。

缺点

  1. 我们正在数据集配置中添加自定义数据,并希望它与Chart.js所做的任何操作不冲突。数据Chart.js预计不会在那里,但是从2.8开始,也不会破坏它。