Chart.js - 绘制任意垂直线

Fre*_*rik 56 javascript chart.js

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

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

在此输入图像描述

pot*_*ngs 77

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

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


预习

在此输入图像描述


HTML

<div>
    <canvas id="LineWithLine" width="600" height="400"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

脚本

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
});
Run Code Online (Sandbox Code Playgroud)

选项属性lineAtIndex控制在哪一点绘制线.

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

  • 这是一个很好的解决方案.你能为chart js version 2.1.6更新这个吗? (10认同)
  • 谢谢@potatopeelings,这正是我想要的.我没有足够的代表来支持你,但显然我愿意. (2认同)
  • @Sheetal - 不太明白.您可能想要发布您要查找的图像.干杯! 此外,新版本的Chart.js(v2.1.x)现已发布.以上答案适用于v1.x. (2认同)

Tom*_*řák 45

为chartjs.org 2.5版共享我的解决方案.我想使用插件,使实现可重用.

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);
Run Code Online (Sandbox Code Playgroud)

用法很简单:

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

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

  • 虽然我赞成这个解决方案,但它确实有一个非常丑陋的限制,因为不可能在索引之间的值处添加行。但事实证明这是一个很棒的教程。 (3认同)
  • 这太棒了,高度可重复使用!好方案!+1 (2认同)

小智 7

在 Chart.js 3.8.0中,我使用了带有时间线 (xAxis) 和百分比 (yAxis) 的折线图/条形图的组合。查看文档

数据集配置提供了一个选项来设置maxBarThickness(我已应用 2),然后将 y 轴的最大值应用于条形图的每个数据条目。

数据集配置示例:

datasets: [
  {
    type: 'line'
    data: [
      {x: "2022-07-18", y: 10},
      {x: "2022-07-19", y: 60},
      {x: "2022-07-20", y: 30}
    ],
    ....
  },
  {
    type: 'bar',
    data: [
      {x: "2022-07-19", y: 100}
    ],
    maxBarThickness: 2,
    ...
  }
]

Run Code Online (Sandbox Code Playgroud)

输出示例:

在此输入图像描述


Bra*_*son 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);
};
Run Code Online (Sandbox Code Playgroud)


phi*_*ifi 5

我强烈建议使用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"
            }
          }
        ]
      }
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

在这里查看更多详细信息:https : //stackoverflow.com/a/36431041


Gra*_*mey 5

这是一支笔,无需使用 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 开始,也没有破坏它。