4

我使用 chart.js 版本 3.x 实现了以下图表。

https://jsfiddle.net/Lxya0u98/12/

我的图表中有多个数据集来实现我想要的行为。

我面临数据集重叠的问题。在图表中,我已经结束了blue color line与数据集的重叠green color dot。有没有办法避免这个问题?

我有以下两个数据集:

// Data set for the Big Dot
{
   showLine: false,
   borderWidth: 0,
   lineTension: 0,
   borderColor: colorVal,
   backgroundColor: colorVal,
   pointBackgroundColor: colorVal,
   pointBorderColor: colorVal,
   pointBorderWidth: 2,
   pointRadius: 15,
};

// Data set for the Connecting Lines
{
   showLine: true,
   lineTension: 0,
   borderWidth: 5,
   borderColor: colorVal,
   pointRadius: 0,
   pointBorderWidth: 0,
   spanGaps: true,
};

数据集是否有 Z 索引,以便它们出现在堆栈中前一个的顶部?

4

2 回答 2

7

该选项dataset.order具有与 z-index 类似的效果。

  • order首先绘制较高的数据集
  • 无序或低序的数据集最后绘制,因此出现在顶部

因此,添加order: 1到您的线数据集应该可以解决问题。

var newDataLine = {
  ...
  order: 1
};
于 2020-12-26T08:22:40.507 回答
1

您可以按以下方式进行,而不是定义多个数据集:

  • 首先将折线图转换为散点图。
  • 然后使用Plugin Core API直接在画布上绘制线条。API 提供了一系列可用于执行自定义代码的钩子。您可以使用beforeDraw钩子在数据点之间和图表的开放端绘制不同颜色的连接线。

请注意,您必须进行定义xAxes.ticks.max才能获得图表右侧的开端线。

请看下面的可运行代码片段,看看它是如何工作的。

new Chart('line-chart', {
  type: "scatter",
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      var dataset = chart.data.datasets[0];
      var y = yAxis.getPixelForValue(0);
      dataset.data.forEach((value, index) => {
        var xFrom = xAxis.getPixelForValue(value.x);
        var xTo;
        if (index + 1 < dataset.data.size) {
          xTo = xAxis.getPixelForValue(dataset.data[index + 1].x);
        } else {
          xTo = xAxis.right;
        }        
        ctx.strokeStyle = dataset.backgroundColor[index];
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.moveTo(xFrom, y);
        ctx.lineTo(xTo, y);
        ctx.stroke();        
      });
      ctx.restore();
    }
  }],
  data: {
    datasets: [{
      data: [
        { x: 0, y: 0 },
        { x: 1, y: 0 },
        { x: 2, y: 0 }
      ],
      backgroundColor: ['red', 'blue', 'green'],
      borderColor: ['red', 'blue', 'green'],
      pointRadius: 8,
      pointHoverRadius: 8,
    }],
  },
  options: {
    layout: {
      padding: {
        left: 10,
        right: 10
      }
    },
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    scales: {
      yAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          display: false,
        }
      }],
      xAxes: [{
        ticks: {
          display: false,
          max: 3
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="line-chart" height="30"></canvas>

于 2020-12-25T11:32:19.297 回答