Chart.js如何仅将线高设置为点?

时间:2018-12-11 10:03:29

标签: javascript charts chart.js

如何仅设置线高直到点?我使用了'gridLines:display:false',但它隐藏了所有行。在下面的图片中应该是

enter image description here

1 个答案:

答案 0 :(得分:1)

它不是Chart.js中的本机选项,但是您可以通过插件自己实现。请参见下面的代码中的注释。

%timeit { col: len(set(map(type, dfl[col])))>1 for col in dfl.columns}
#124 ms ± 15.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
new Chart(document.getElementById('chart'), {
  type: 'line',
  data: {
    labels: [0, 1, 2, 3, 4, 5],
    datasets: [{
      label: 'series 1',
      data: [0, 2, 4, 3, 1, 0]
    }]
  },
  options: {
    maintainAspectRatio: false,
    scales: {
      xAxes: [{
        gridLines: {
          display: false, // must be false since we're going to draw our own 'gridlines'!
          color: 'rgba(255, 0, 0, .2)', // can still set the colour.
          lineWidth: 5 // can still set the width.
        }
      }],
      yAxes: [{
        gridLines: {
          display: false
        },
        ticks: {
          beginAtZero: true
        }
      }]
    }
  },
  plugins: [{ // this is the magical bit :)
    afterRender: function(c, options) {
      let meta = c.getDatasetMeta(0),
        max;
      c.ctx.save();
      c.ctx.strokeStyle = c.config.options.scales.xAxes[0].gridLines.color;
      c.ctx.lineWidth = c.config.options.scales.xAxes[0].gridLines.lineWidth;
      c.ctx.beginPath();
      meta.data.forEach(function(e) {
        if (max == undefined || c.config.data.datasets[0].data[e._index] > max) {
          max = c.config.data.datasets[0].data[e._index];
        }
        c.ctx.moveTo(e._model.x, meta.dataset._scale.bottom);
        c.ctx.lineTo(e._model.x, e._model.y);
      });
      c.ctx.textBaseline = 'top';
      c.ctx.textAlign = 'right';
      c.ctx.fillStyle = 'black';
      c.ctx.fillText('Max value: ' + max, c.width - 10, 10);
      c.ctx.stroke();
      c.ctx.restore();
    }
  }]
});